diff --git a/.gitignore b/.gitignore
index 79ea050..fbef39d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -41,3 +41,40 @@ target
ehthumbs.db
Icon?
Thumbs.db
+
+
+# Built application files
+*.apk
+*.ap_
+
+# Files for the Dalvik VM
+*.dex
+
+# Java class files
+*.class
+
+# Generated files
+bin/
+gen/
+
+# Gradle files
+.gradle/
+build/
+
+# Local configuration file (sdk path, etc)
+local.properties
+
+# Proguard folder generated by Eclipse
+proguard/
+
+# Log Files
+*.log
+
+# Android Studio Navigation editor temp files
+.navigation/
+.idea
+*.iml
+
+# Android Studio captures folder
+captures/
+
diff --git a/AndroidArduinoOpenCV/res/values/strings.xml b/AndroidArduinoOpenCV/res/values/strings.xml
index 699c00a..b0d48b0 100644
--- a/AndroidArduinoOpenCV/res/values/strings.xml
+++ b/AndroidArduinoOpenCV/res/values/strings.xml
@@ -4,19 +4,20 @@
Roogle roverRoogle rover
-
-
+
+
+
Send
- You are not connected to a device
+ You are not connected to a device.Bluetooth was not enabled. Leaving Bluetooth Chat.
- connecting...
- connected:
- not connected
+ Connecting...
+ Connected:
+ Not connected.
- scanning for devices...
- select a device to connect
+ Scanning for devices...
+ Select a device to connectNo devices have been pairedNo devices foundPaired Devices
@@ -26,4 +27,4 @@
Connect a deviceMake discoverable
-
\ No newline at end of file
+
diff --git a/GestureVoiceCommander/res/drawable-hdpi/ic_launcher.png b/GestureVoiceCommander/res/drawable-hdpi/ic_launcher.png
index d62b72a..c609872 100644
Binary files a/GestureVoiceCommander/res/drawable-hdpi/ic_launcher.png and b/GestureVoiceCommander/res/drawable-hdpi/ic_launcher.png differ
diff --git a/GestureVoiceCommander/src/com/androidmontreal/gesture/commander/RoverLexicon.java b/GestureVoiceCommander/src/com/androidmontreal/gesture/commander/RoverLexicon.java
index ffcd4dc..f89c616 100644
--- a/GestureVoiceCommander/src/com/androidmontreal/gesture/commander/RoverLexicon.java
+++ b/GestureVoiceCommander/src/com/androidmontreal/gesture/commander/RoverLexicon.java
@@ -1,191 +1,192 @@
package com.androidmontreal.gesture.commander;
import java.util.ArrayList;
-
+import java.util.Locale;
public class RoverLexicon {
- private int language;
- private int timer = 5;
-
- /*
- * Languages
- */
- public static final int EN = 1000;
- public static final int FR = 1001;
- public static final String EN_CARRIER_PHRASE = "I will tell the robot: ";
- public static final String FR_CARRIER_PHRASE = "Je vais dire au robo: ";
-
-
- /*
- * Commands, use the order of these constants for
- * the precedence order of the commands
- * (STOP has the highest precedence)
- */
- public static final int STOP = 0;
- public static final int EXPLORE = 1;
- public static final int FORWARD = 2;
- public static final int REVERSE = 3;
- public static final int TURNRIGHT = 6;
- public static final int TURNLEFT = 7;
- public static final int ROTATERIGHT = 4;
- public static final int ROTATELEFT = 5;
-
- private ArrayList en;
- private ArrayList fr;
-
- private int mCommandToExecute;
-
- public String stop() {
- return "S";
- }
-
- public String explore() {
- return "E";
- }
-
- public String forward() {
- return "1F2F";
- }
-
- public String reverse() {
- return "1R2R";
- }
-
- public String turnRight() {
- return "1F";
- }
-
- public String turnLeft() {
- return "2F";
- }
-
- public String rotateRight() {
- return "1F2R";
- }
-
- public String rotateLeft() {
- return "1R2F";
- }
-
- public void defineLanguages() {
- en = new ArrayList();
- en.add(STOP, "stop:wait:don't:no:damn");
- en.add(EXPLORE, "explore:try");
- en.add(FORWARD, "forward:ahead");
- en.add(REVERSE, "reverse:back");
- en.add(ROTATERIGHT, "rotate&right");
- en.add(ROTATELEFT, "rotate&left");
- en.add(TURNRIGHT, "right");
- en.add(TURNLEFT, "left");
-
-
- fr = new ArrayList();
- fr.add(STOP, "arrete:pas:voyons:merde");
- fr.add(EXPLORE, "explore");
- fr.add(FORWARD, "avance");
- fr.add(REVERSE, "recule");
- fr.add(ROTATERIGHT, "rotate&droit");
- fr.add(ROTATELEFT, "rotate&gauche");
- fr.add(TURNRIGHT, "droit");
- fr.add(TURNLEFT, "gauche");
-
-
- }
-
- public String execute(int commandInteger) {
- switch (commandInteger) {
- case STOP:
- return stop();
- case EXPLORE:
- return explore();
- case FORWARD:
- return forward();
- case REVERSE:
- return reverse();
- case TURNRIGHT:
- return turnRight();
- case TURNLEFT:
- return turnLeft();
- case ROTATERIGHT:
- return rotateRight();
- case ROTATELEFT:
- return rotateLeft();
- default:
- return stop();
- }
- }
-
- public String guessWhatToDo(String command) {
- command = command.toLowerCase();
- int commandToExecute = STOP;
- String commandForHumans = command;
-
- ArrayList humancommands = en;
- if (language == FR) {
- humancommands = fr;
- }
- for (int i = 0; i < humancommands.size(); i++) {
- String[] andwords = humancommands.get(i).split("&");
- String[] orwords = humancommands.get(i).split(":");
- /*
- * If there are AND words, then check first to see if it matches all
- * words
- */
- if (andwords.length > 1) {
- int wordsfound = 0;
- commandForHumans = andwords[0];
- for (int k = 0; k < andwords.length; k++) {
- if (command.contains(andwords[k])) {
- wordsfound++;
- }
- }
- if (wordsfound >= andwords.length) {
- commandToExecute = i;
- return commandForHumans;
- }
- }
- /*
- * Then if a command hasn't been issued, check for the OR words.
- */
- if(orwords.length > 0){
- commandForHumans = orwords[0];
- for (int k = 0; k < orwords.length; k++) {
- if (command.contains(orwords[k])) {
- commandToExecute = i;
- return commandForHumans;
- }
- }
- }
-
-
- }
- mCommandToExecute = commandToExecute;
- return commandForHumans;
- }
- public String executeGuess(){
- if(mCommandToExecute >= 0){
- return execute(mCommandToExecute);
- }
- return "";
- }
-
- public RoverLexicon(int language, int timer) {
- super();
- defineLanguages();
- this.language = language;
- this.timer = timer;
- }
- public RoverLexicon(int language) {
- super();
- defineLanguages();
- this.language = language;
- this.timer = 5;
- }
- public RoverLexicon() {
- super();
- defineLanguages();
- this.language = EN;
- this.timer = 5;
- }
+ private int language;
+ private int timer = 5;
+
+ /*
+ * Languages
+ */
+ public static final int EN = 1000;
+ public static final int FR = 1001;
+ public static final String EN_CARRIER_PHRASE = "I will tell the robot: ";
+ public static final String FR_CARRIER_PHRASE = "Je vais dire au robo: ";
+
+ /*
+ * Commands, use the order of these constants for the precedence order of the
+ * commands (STOP has the highest precedence)
+ */
+ public static final int STOP = 0;
+ public static final int EXPLORE = 1;
+ public static final int FORWARD = 2;
+ public static final int REVERSE = 3;
+ public static final int TURNRIGHT = 6;
+ public static final int TURNLEFT = 7;
+ public static final int ROTATERIGHT = 4;
+ public static final int ROTATELEFT = 5;
+
+ private ArrayList en;
+ private ArrayList fr;
+
+ private int mCommandToExecute;
+
+ public String stop() {
+ return "S";
+ }
+
+ public String explore() {
+ return "E";
+ }
+
+ public String forward() {
+ return "1F2F";
+ }
+
+ public String reverse() {
+ return "1R2R";
+ }
+
+ public String turnRight() {
+ return "1F";
+ }
+
+ public String turnLeft() {
+ return "2F";
+ }
+
+ public String rotateRight() {
+ return "1F2R";
+ }
+
+ public String rotateLeft() {
+ return "1R2F";
+ }
+
+ public void defineLanguages() {
+ en = new ArrayList();
+ en.add(STOP, "stop:wait:don't:no:damn");
+ en.add(EXPLORE, "explore:try");
+ en.add(FORWARD, "forward:ahead");
+ en.add(REVERSE, "reverse:back");
+ en.add(ROTATERIGHT, "rotate&right");
+ en.add(ROTATELEFT, "rotate&left");
+ en.add(TURNRIGHT, "right");
+ en.add(TURNLEFT, "left");
+
+ fr = new ArrayList();
+ fr.add(STOP, "arrête:arrêter:arrêté:arrêter:arrêtez:pas:voyons:voyant:m****:merde:zut:non:stop");
+ fr.add(EXPLORE, "explore:explorer");
+ fr.add(FORWARD, "avance:tu dois:tu dois:te doi:tournoi:tout droit:avanc:forward");
+ fr.add(REVERSE, "recule:recul:reverse:arrière");
+ fr.add(ROTATERIGHT, "pivoter vers la droite:vers la droite:pilot:pivot:rotate&droit");
+ fr.add(ROTATELEFT, "pivoter vers la gauche:vers la gauche:rotate&gauche");
+ fr.add(TURNRIGHT, "à la droite:droite:droit:right");
+ fr.add(TURNLEFT, "à la gauche:gauche:left");
+
+ }
+
+ public String execute(int commandInteger) {
+ switch (commandInteger) {
+ case STOP:
+ return stop();
+ case EXPLORE:
+ return explore();
+ case FORWARD:
+ return forward();
+ case REVERSE:
+ return reverse();
+ case TURNRIGHT:
+ return turnRight();
+ case TURNLEFT:
+ return turnLeft();
+ case ROTATERIGHT:
+ return rotateRight();
+ case ROTATELEFT:
+ return rotateLeft();
+ default:
+ return stop();
+ }
+ }
+
+ public String guessWhatToDo(String command) {
+ command = command.toLowerCase();
+ int commandToExecute = STOP;
+ String commandForHumans = command;
+
+ ArrayList humancommands = en;
+ if (language == FR) {
+ humancommands = fr;
+ }
+ for (int i = 0; i < humancommands.size(); i++) {
+ String[] andwords = humancommands.get(i).split("&");
+ String[] orwords = humancommands.get(i).split(":");
+ /*
+ * If there are AND words, then check first to see if it matches all words
+ */
+ if (andwords.length > 1) {
+ int wordsfound = 0;
+ commandForHumans = andwords[0];
+ for (int k = 0; k < andwords.length; k++) {
+ if (command.contains(andwords[k])) {
+ wordsfound++;
+ }
+ }
+ if (wordsfound >= andwords.length) {
+ commandToExecute = i;
+ return commandForHumans;
+ }
+ }
+ /*
+ * Then if a command hasn't been issued, check for the OR words.
+ */
+ if (orwords.length > 0) {
+ commandForHumans = orwords[0];
+ for (int k = 0; k < orwords.length; k++) {
+ if (command.contains(orwords[k])) {
+ commandToExecute = i;
+ return commandForHumans;
+ }
+ }
+ }
+
+ }
+ mCommandToExecute = commandToExecute;
+ return commandForHumans;
+ }
+
+ public String executeGuess() {
+ if (mCommandToExecute >= 0) {
+ return execute(mCommandToExecute);
+ }
+ return "";
+ }
+
+ public RoverLexicon(int language, int timer) {
+ super();
+ defineLanguages();
+ this.language = language;
+ this.timer = timer;
+ }
+
+ public RoverLexicon(int language) {
+ super();
+ defineLanguages();
+ this.language = language;
+ this.timer = 5;
+ }
+
+ public RoverLexicon() {
+ super();
+ defineLanguages();
+ if (Locale.getDefault().getLanguage().contains("fr")) {
+ this.language = FR;
+ } else {
+ this.language = EN;
+ }
+ this.timer = 5;
+ }
}
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..d8413ce
--- /dev/null
+++ b/README.md
@@ -0,0 +1,11 @@
+This project contains sample code for making a arduino robot recognize dots in front of it using OpenCV, send its results to MyRobots.com and also control the robot using another Android using either voice or gestures to tell the robot to turn or do other things.
+
+The Tutorial folder breaks it down into manageble chunks:
+* [Tutorial](Tutorial)
+
+Issues which explain the code and let you see the diffs between each step:
+* https://github.com/AndroidMontreal/UpAndRunningWithAndroid/issues?milestone=1&state=open
+
+The other folders are the code from our cloud robotics project (forked from google code to github since it seems to be easier for people to set up at hackathons)
+* https://code.google.com/p/roogle-darwin/
+
diff --git a/Tutorial/NOTICE b/Tutorial/LICENSE
similarity index 100%
rename from Tutorial/NOTICE
rename to Tutorial/LICENSE
diff --git a/Tutorial/MakeItListenAndRepeat.apk b/Tutorial/MakeItListenAndRepeat.apk
index ace415b..5b08362 100644
Binary files a/Tutorial/MakeItListenAndRepeat.apk and b/Tutorial/MakeItListenAndRepeat.apk differ
diff --git a/Tutorial/MakeItUnderstandVoiceAndGestures.apk b/Tutorial/MakeItUnderstandVoiceAndGestures.apk
index 315ce7f..483a76e 100644
Binary files a/Tutorial/MakeItUnderstandVoiceAndGestures.apk and b/Tutorial/MakeItUnderstandVoiceAndGestures.apk differ
diff --git a/Tutorial/MakeItUnderstandVoiceGesturesAndWatch.apk b/Tutorial/MakeItUnderstandVoiceGesturesAndWatch.apk
new file mode 100644
index 0000000..7f63d0b
Binary files /dev/null and b/Tutorial/MakeItUnderstandVoiceGesturesAndWatch.apk differ
diff --git a/Tutorial/MakeItUnderstandWatch.apk b/Tutorial/MakeItUnderstandWatch.apk
new file mode 100644
index 0000000..ad465e8
Binary files /dev/null and b/Tutorial/MakeItUnderstandWatch.apk differ
diff --git a/Tutorial/README.md b/Tutorial/README.md
new file mode 100644
index 0000000..85b3ff6
--- /dev/null
+++ b/Tutorial/README.md
@@ -0,0 +1,14 @@
+This is essentailly a three part tutorial to make an Android into a remote control (voice, touch or watch controlled) for a robot, garage opener, stereo etc
+
+The steps are in this milestone:
+https://github.com/AndroidMontreal/UpAndRunningWithAndroid/milestones/Up%20and%20Running%20
+
+Step one - Make it Talk
+
+Step two - Make it Listen
+
+Step three - Make it Understand
+
+Bonus credit:
+
+Step three - Control it with a watch
diff --git a/Tutorial/app/build.gradle b/Tutorial/app/build.gradle
new file mode 100644
index 0000000..82a2a5e
--- /dev/null
+++ b/Tutorial/app/build.gradle
@@ -0,0 +1,26 @@
+apply plugin: 'com.android.application'
+
+android {
+ compileSdkVersion 18
+ buildToolsVersion "23.0.0"
+
+ defaultConfig {
+ applicationId "com.androidmontreal.gesturevoicecommander"
+ minSdkVersion 18
+ compileSdkVersion 21
+ targetSdkVersion 23
+ }
+
+ dependencies {
+ wearApp project(':wear')
+ compile 'com.google.android.gms:play-services:7.8.0'
+ compile 'watch.nudge.phonegesturelibrary:phone-gest-lib:0.8.4'
+ }
+
+ buildTypes {
+ release {
+ minifyEnabled false
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
+ }
+ }
+}
diff --git a/Tutorial/AndroidManifest.xml b/Tutorial/app/src/main/AndroidManifest.xml
similarity index 56%
rename from Tutorial/AndroidManifest.xml
rename to Tutorial/app/src/main/AndroidManifest.xml
index 30fc789..4fb7b29 100644
--- a/Tutorial/AndroidManifest.xml
+++ b/Tutorial/app/src/main/AndroidManifest.xml
@@ -1,4 +1,4 @@
-
+
-
+ package="com.androidmontreal.gesturevoicecommander">
+
+
+
+
-
+
+
-
+
-
+ android:name=".GestureBuilderActivity"
+ android:label="@string/application_name">
-
+ android:label="Text To Speech">
-
+ android:label="Speech Recognition">
+ android:label="Speech Recognition" >
@@ -51,6 +50,16 @@
+
+
+
+
-
\ No newline at end of file
+
diff --git a/Tutorial/src/com/androidmontreal/gesturevoicecommander/CreateGestureActivity.java b/Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/CreateGestureActivity.java
similarity index 98%
rename from Tutorial/src/com/androidmontreal/gesturevoicecommander/CreateGestureActivity.java
rename to Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/CreateGestureActivity.java
index 436d970..79d129a 100644
--- a/Tutorial/src/com/androidmontreal/gesturevoicecommander/CreateGestureActivity.java
+++ b/Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/CreateGestureActivity.java
@@ -39,7 +39,7 @@ public class CreateGestureActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
-
+
setContentView(R.layout.create_gesture);
mDoneButton = findViewById(R.id.done);
@@ -51,7 +51,7 @@ protected void onCreate(Bundle savedInstanceState) {
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
-
+
if (mGesture != null) {
outState.putParcelable("gesture", mGesture);
}
@@ -60,7 +60,7 @@ protected void onSaveInstanceState(Bundle outState) {
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
-
+
mGesture = savedInstanceState.getParcelable("gesture");
if (mGesture != null) {
final GestureOverlayView overlay =
@@ -99,15 +99,15 @@ public void addGesture(View v) {
}
finish();
-
+
}
-
+
@SuppressWarnings({"UnusedDeclaration"})
public void cancelGesture(View v) {
setResult(RESULT_CANCELED);
finish();
}
-
+
private class GesturesProcessor implements GestureOverlayView.OnGestureListener {
public void onGestureStarted(GestureOverlayView overlay, MotionEvent event) {
mDoneButton.setEnabled(false);
diff --git a/Tutorial/src/com/androidmontreal/gesturevoicecommander/GestureBuilderActivity.java b/Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/GestureBuilderActivity.java
similarity index 92%
rename from Tutorial/src/com/androidmontreal/gesturevoicecommander/GestureBuilderActivity.java
rename to Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/GestureBuilderActivity.java
index 338e015..6c657db 100644
--- a/Tutorial/src/com/androidmontreal/gesturevoicecommander/GestureBuilderActivity.java
+++ b/Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/GestureBuilderActivity.java
@@ -64,7 +64,7 @@ public class GestureBuilderActivity extends ListActivity {
private static final int DIALOG_RENAME_GESTURE = 1;
private static final int REQUEST_NEW_GESTURE = 1;
-
+
// Type: long (id)
private static final String GESTURES_INFO_ID = "gestures.info_id";
@@ -97,7 +97,7 @@ protected void onCreate(Bundle savedInstanceState) {
if (sStore == null) {
// sStore = GestureLibraries.fromFile(mStoreFile);
- sStore = GestureLibraries.fromRawResource(this, R.raw.gestures);
+ sStore = GestureLibraries.fromRawResource(this, R.raw.gestures);
}
mEmpty = (TextView) findViewById(android.R.id.empty);
loadGestures();
@@ -113,7 +113,7 @@ static GestureLibrary getStore() {
public void reloadGestures(View v) {
loadGestures();
}
-
+
@SuppressWarnings({"UnusedDeclaration"})
public void addGesture(View v) {
Intent intent = new Intent(this, CreateGestureActivity.class);
@@ -123,7 +123,7 @@ public void addGesture(View v) {
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
-
+
if (resultCode == RESULT_OK) {
switch (requestCode) {
case REQUEST_NEW_GESTURE:
@@ -136,7 +136,7 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
private void loadGestures() {
if (mTask != null && mTask.getStatus() != GesturesLoadTask.Status.FINISHED) {
mTask.cancel(true);
- }
+ }
mTask = (GesturesLoadTask) new GesturesLoadTask().execute();
}
@@ -174,7 +174,8 @@ protected void onRestoreInstanceState(Bundle state) {
long id = state.getLong(GESTURES_INFO_ID, -1);
if (id != -1) {
final Set entries = sStore.getGestureEntries();
-out: for (String name : entries) {
+ out:
+ for (String name : entries) {
for (Gesture gesture : sStore.getGestures(name)) {
if (gesture.getID() == id) {
mCurrentRenameGesture = new NamedGesture();
@@ -188,9 +189,7 @@ protected void onRestoreInstanceState(Bundle state) {
}
@Override
- public void onCreateContextMenu(ContextMenu menu, View v,
- ContextMenu.ContextMenuInfo menuInfo) {
-
+ public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
@@ -202,8 +201,7 @@ public void onCreateContextMenu(ContextMenu menu, View v,
@Override
public boolean onContextItemSelected(MenuItem item) {
- final AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo)
- item.getMenuInfo();
+ final AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
final NamedGesture gesture = (NamedGesture) menuInfo.targetView.getTag();
switch (item.getItemId()) {
@@ -254,18 +252,18 @@ public void onCancel(DialogInterface dialog) {
}
});
builder.setNegativeButton(getString(R.string.cancel_action),
- new Dialog.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- cleanupRenameDialog();
+ new Dialog.OnClickListener() {
+ public void onClick(DialogInterface dialog, int which) {
+ cleanupRenameDialog();
+ }
}
- }
);
builder.setPositiveButton(getString(R.string.rename_action),
- new Dialog.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- changeGestureName();
+ new Dialog.OnClickListener() {
+ public void onClick(DialogInterface dialog, int which) {
+ changeGestureName();
+ }
}
- }
);
builder.setView(layout);
return builder.create();
@@ -333,8 +331,8 @@ protected void onPreExecute() {
findViewById(R.id.addButton).setEnabled(false);
findViewById(R.id.reloadButton).setEnabled(false);
-
- mAdapter.setNotifyOnChange(false);
+
+ mAdapter.setNotifyOnChange(false);
mAdapter.clear();
}
@@ -352,8 +350,7 @@ protected Integer doInBackground(Void... params) {
if (isCancelled()) break;
for (Gesture gesture : store.getGestures(name)) {
- final Bitmap bitmap = gesture.toBitmap(mThumbnailSize, mThumbnailSize,
- mThumbnailInset, mPathColor);
+ final Bitmap bitmap = gesture.toBitmap(mThumbnailSize, mThumbnailSize, mThumbnailInset, mPathColor);
final NamedGesture namedGesture = new NamedGesture();
namedGesture.gesture = gesture;
namedGesture.name = name;
@@ -391,8 +388,7 @@ protected void onPostExecute(Integer result) {
if (result == STATUS_NO_STORAGE) {
getListView().setVisibility(View.GONE);
mEmpty.setVisibility(View.VISIBLE);
- mEmpty.setText(getString(R.string.gestures_error_loading,
- mStoreFile.getAbsolutePath()));
+ mEmpty.setText(getString(R.string.gestures_error_loading, mStoreFile.getAbsolutePath()));
} else {
findViewById(R.id.addButton).setEnabled(true);
findViewById(R.id.reloadButton).setEnabled(true);
@@ -408,8 +404,7 @@ static class NamedGesture {
private class GesturesAdapter extends ArrayAdapter {
private final LayoutInflater mInflater;
- private final Map mThumbnails = Collections.synchronizedMap(
- new HashMap());
+ private final Map mThumbnails = Collections.synchronizedMap(new HashMap());
public GesturesAdapter(Context context) {
super(context, 0);
@@ -431,8 +426,7 @@ public View getView(int position, View convertView, ViewGroup parent) {
label.setTag(gesture);
label.setText(gesture.name);
- label.setCompoundDrawablesWithIntrinsicBounds(mThumbnails.get(gesture.gesture.getID()),
- null, null, null);
+ label.setCompoundDrawablesWithIntrinsicBounds(mThumbnails.get(gesture.gesture.getID()), null, null, null);
return convertView;
}
diff --git a/Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/practice/MakeItListenAndRepeat.java b/Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/practice/MakeItListenAndRepeat.java
new file mode 100644
index 0000000..73920cb
--- /dev/null
+++ b/Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/practice/MakeItListenAndRepeat.java
@@ -0,0 +1,157 @@
+package com.androidmontreal.gesturevoicecommander.practice;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+
+import android.app.Activity;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.os.Bundle;
+import android.speech.RecognizerIntent;
+import android.speech.tts.TextToSpeech;
+import android.speech.tts.TextToSpeech.OnInitListener;
+import android.util.Log;
+import android.widget.Toast;
+
+import com.androidmontreal.gesturevoicecommander.R;
+
+/**
+ * Building on what we saw in MakeItTalk, now lets make it Listen. Here is some
+ * super simple code that uses the VoiceRecognition Intent to recognize what the
+ * user says, and then uses Text To Speech to tell the user what it might have
+ * heard.
+ *
+ * @author cesine
+ */
+public class MakeItListenAndRepeat extends Activity implements OnInitListener {
+ private static final String TAG = "MakeItListen";
+ private static final int RETURN_FROM_VOICE_RECOGNITION_REQUEST_CODE = 341;
+ /**
+ * Talk to the user
+ */
+ private TextToSpeech mTts;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+
+ mTts = new TextToSpeech(this, this);
+ }
+
+ protected void promptTheUserToTalk() {
+ if (isIntentAvailable(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)) {
+ this.speak(getString(R.string.im_listening));
+ } else {
+ this.speak(getString(R.string.i_cant_listen));
+ }
+ }
+
+ /**
+ * Fire an intent to start the voice recognition activity.
+ */
+ private void startVoiceRecognitionActivity() {
+ Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
+ intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
+ intent.putExtra(RecognizerIntent.EXTRA_PROMPT, getString(R.string.im_listening));
+ if (isIntentAvailable(intent)) {
+ startActivityForResult(intent, RETURN_FROM_VOICE_RECOGNITION_REQUEST_CODE);
+ } else {
+ Log.w(TAG, "This device doesn't have speech recognition, maybe its an emulator or a phone from china without google products?");
+ }
+ }
+
+ /**
+ * Handle the results from the voice recognition activity.
+ */
+ @Override
+ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+ if (requestCode == RETURN_FROM_VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
+ /*
+ * Populate the wordsList with the String values the recognition engine
+ * thought it heard, and then Toast them to the user and say them out
+ * loud.
+ */
+ ArrayList matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
+ for (int iMightHaveHeardThis = 0; iMightHaveHeardThis < matches.size(); iMightHaveHeardThis++) {
+
+ /* Build a carrierPhrase if you want it to make some sense */
+ String carrierPhrase = getString(R.string.i_might_have_heard);
+ if (iMightHaveHeardThis > 0) {
+ carrierPhrase = getString(R.string.or_maybe);
+ }
+ carrierPhrase += " " + matches.get(iMightHaveHeardThis) + ".";
+
+ Toast.makeText(this, carrierPhrase, Toast.LENGTH_LONG).show();
+ this.speak(carrierPhrase);
+
+ /*
+ * Don't go on forever, it there are too many potential matches don't
+ * say them all
+ */
+ if (iMightHaveHeardThis == 2 && matches.size() > 2) {
+ this.speak(getString(R.string.there_were_others));
+ break;
+ }
+ }
+ }
+ super.onActivityResult(requestCode, resultCode, data);
+ }
+
+ @Override
+ protected void onDestroy() {
+ if (mTts != null) {
+ mTts.stop();
+ mTts.shutdown();
+ }
+ super.onDestroy();
+ }
+
+ @Override
+ public void onInit(int status) {
+ if (status == TextToSpeech.SUCCESS) {
+ int result = mTts.setLanguage(Locale.getDefault());
+ if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
+ Log.e(TAG, "Language is not available.");
+ Toast.makeText(this,
+ "The " + Locale.getDefault().getDisplayLanguage()
+ + " TextToSpeech isn't installed, you can go into the "
+ + "\nAndroid's settings in the "
+ + "\nVoice Input and Output menu to turn it on. ",
+ Toast.LENGTH_LONG).show();
+ } else {
+ // everything is working.
+ promptTheUserToTalk();
+ startVoiceRecognitionActivity();
+ }
+ } else {
+ Toast.makeText(this,
+ "Sorry, I can't talk to you because "
+ + "I could not initialize TextToSpeech.", Toast.LENGTH_LONG)
+ .show();
+ }
+ }
+
+ public boolean speak(String message) {
+ if (mTts != null) {
+ mTts.speak(message, TextToSpeech.QUEUE_ADD, null);
+ } else {
+ Toast.makeText(this, "Sorry, I can't speak to you: " + message, Toast.LENGTH_LONG).show();
+ }
+ return true;
+ }
+
+ public boolean isIntentAvailable(String action) {
+ final Intent intent = new Intent(action);
+ return isIntentAvailable(intent);
+ }
+
+ public boolean isIntentAvailable(final Intent intent) {
+ final PackageManager packageManager = this.getPackageManager();
+ List list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
+ return list.size() > 0;
+ }
+
+}
diff --git a/Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/practice/MakeItTalk.java b/Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/practice/MakeItTalk.java
new file mode 100644
index 0000000..fbb96c4
--- /dev/null
+++ b/Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/practice/MakeItTalk.java
@@ -0,0 +1,64 @@
+package com.androidmontreal.gesturevoicecommander.practice;
+
+import java.util.Locale;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.speech.tts.TextToSpeech;
+import android.speech.tts.TextToSpeech.OnInitListener;
+import android.util.Log;
+import android.widget.Toast;
+
+import com.androidmontreal.gesturevoicecommander.R;
+
+public class MakeItTalk extends Activity implements OnInitListener {
+ private static final String TAG = "MakeItTalk";
+ /**
+ * Talk to the user
+ */
+ private TextToSpeech mTts;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+
+ mTts = new TextToSpeech(this, this);
+ }
+
+ protected void sayFirstWords() {
+ mTts.speak(getString(R.string.my_first_words), TextToSpeech.QUEUE_ADD, null);
+ }
+
+ @Override
+ protected void onDestroy() {
+ if (mTts != null) {
+ mTts.stop();
+ mTts.shutdown();
+ }
+ super.onDestroy();
+ }
+
+ @Override
+ public void onInit(int status) {
+ if (status == TextToSpeech.SUCCESS) {
+ int result = mTts.setLanguage(Locale.getDefault());
+ if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
+ Log.e(TAG, "Language is not available.");
+ Toast.makeText(this,
+ "The " + Locale.getDefault().getDisplayLanguage()
+ + " TextToSpeech isn't installed, you can go into the "
+ + "\nAndroid's settings in the "
+ + "\nVoice Input and Output menu to turn it on. ",
+ Toast.LENGTH_LONG).show();
+ } else {
+ // everything is working.
+ sayFirstWords();
+ }
+ } else {
+ Toast.makeText(this,
+ "Sorry, I can't talk to you because "
+ + "I could not initialize TextToSpeech.", Toast.LENGTH_LONG)
+ .show();
+ }
+ }
+}
diff --git a/Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/practice/MakeItUnderstandGestures.java b/Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/practice/MakeItUnderstandGestures.java
new file mode 100644
index 0000000..0ef4526
--- /dev/null
+++ b/Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/practice/MakeItUnderstandGestures.java
@@ -0,0 +1,240 @@
+package com.androidmontreal.gesturevoicecommander.practice;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.gesture.Gesture;
+import android.gesture.GestureLibraries;
+import android.gesture.GestureLibrary;
+import android.gesture.GestureOverlayView;
+import android.gesture.Prediction;
+import android.gesture.GestureOverlayView.OnGesturePerformedListener;
+import android.os.Bundle;
+import android.speech.RecognizerIntent;
+import android.speech.tts.TextToSpeech;
+import android.speech.tts.TextToSpeech.OnInitListener;
+import android.util.Log;
+import android.view.View;
+import android.widget.Toast;
+
+import com.androidmontreal.gesturevoicecommander.GestureBuilderActivity;
+import com.androidmontreal.gesturevoicecommander.R;
+import com.androidmontreal.gesturevoicecommander.robots.Lexicon;
+
+import watch.nudge.phonegesturelibrary.AbstractPhoneGestureActivity;
+
+/**
+ * Building on what we saw in MakeItListenAndRepeat, now lets make it understand
+ * gestures, or speech (sometimes its too noisy or too public to speak to your
+ * Android). Here is some super simple code that builds on the GestureBuilder
+ * sample code to recognize what the user wants the Android to do, and then use
+ * Text To Speech to tell the user what it might have understood.
+ *
+ * @author cesine
+ */
+public class MakeItUnderstandGestures extends AbstractPhoneGestureActivity implements OnInitListener, OnGesturePerformedListener {
+ private static final String TAG = "MakeItUnderstandGesture";
+ private static final int RETURN_FROM_VOICE_RECOGNITION_REQUEST_CODE = 341;
+ private static final boolean D = true;
+
+ /**
+ * Talk to the user
+ */
+ private TextToSpeech mTts;
+
+ /*
+ * A gesture library we created with the GestureBuilder, saved on the SDCard
+ * and then imported into the res/raw folder of this project
+ */
+ private GestureLibrary gestureLib;
+
+ /* A little lexicon we made for the DFR Rover at Cloud Robotics Hackathon */
+ private Lexicon lexicon;
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+
+ mTts = new TextToSpeech(this, this);
+
+ GestureOverlayView gestureOverlayView = new GestureOverlayView(this);
+ View inflate = getLayoutInflater().inflate(R.layout.commander, null);
+ gestureOverlayView.addView(inflate);
+ gestureOverlayView.addOnGesturePerformedListener(this);
+ // gestureLib = GestureLibraries.fromFile(fileOnYourSDCard);
+ gestureLib = GestureLibraries.fromRawResource(this, R.raw.gestures);
+ if (!gestureLib.load()) {
+ finish();
+ }
+ setContentView(gestureOverlayView);
+
+ lexicon = new Lexicon();
+ }
+
+ protected void promptTheUserToTalk() {
+ if (isIntentAvailable(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)) {
+ this.speak(getString(R.string.im_listening));
+ } else {
+ this.speak(getString(R.string.i_cant_listen));
+ }
+ }
+
+ /**
+ * Fire an intent to start the voice recognition activity.
+ */
+ private void startVoiceRecognitionActivity() {
+ Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
+ intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
+ intent.putExtra(RecognizerIntent.EXTRA_PROMPT, getString(R.string.im_listening));
+ if (isIntentAvailable(intent)) {
+ startActivityForResult(intent, RETURN_FROM_VOICE_RECOGNITION_REQUEST_CODE);
+ } else {
+ Log.w(TAG, "This device doesn't have speech recognition, maybe its an emulator or a phone from china without google products?");
+ }
+ }
+
+ /**
+ * Handle the results from the voice recognition activity.
+ */
+ @Override
+ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+ if (requestCode == RETURN_FROM_VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
+ ArrayList matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
+ /* try to find a robot command in the first match */
+ if (matches.size() > 0) {
+ sendRobotThisCommand(matches.get(0));
+ }
+ }
+ super.onActivityResult(requestCode, resultCode, data);
+ }
+
+ @Override
+ public void onDestroy() {
+ if (mTts != null) {
+ mTts.stop();
+ mTts.shutdown();
+ }
+ super.onDestroy();
+ }
+
+ @Override
+ public void onInit(int status) {
+ if (status == TextToSpeech.SUCCESS) {
+ int result = mTts.setLanguage(Locale.getDefault());
+ if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
+ Log.e(TAG, "Language is not available.");
+ Toast.makeText(this,
+ "The " + Locale.getDefault().getDisplayLanguage()
+ + " TextToSpeech isn't installed, you can go into the "
+ + "\nAndroid's settings in the "
+ + "\nVoice Input and Output menu to turn it on. ",
+ Toast.LENGTH_LONG).show();
+ } else {
+ // everything is working.
+ this.speak(getString(R.string.instructions_to_look_at_menu));
+ }
+ } else {
+ Toast.makeText(this, "Sorry, I can't talk to you because " +
+ "I could not initialize TextToSpeech.", Toast.LENGTH_LONG).show();
+ }
+ }
+
+ public boolean speak(String message) {
+ if (mTts != null) {
+ mTts.speak(message, TextToSpeech.QUEUE_ADD, null);
+ } else {
+ Toast.makeText(this, "Sorry, I can't speak to you: " + message, Toast.LENGTH_LONG).show();
+ }
+ return true;
+ }
+
+ @Override
+ public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
+ ArrayList predictions = gestureLib.recognize(gesture);
+ for (Prediction prediction : predictions) {
+ if (prediction.score > 3.0) {
+ Log.d(TAG, "Detected this gesture " + prediction.name + " with a score of " + prediction.score);
+ }
+ }
+ if (predictions.size() > 0) {
+ sendRobotThisCommand(predictions.get(0).name);
+ }
+ }
+ @Override
+ public void onSnap() {
+ sendRobotThisCommand(lexicon.stop());
+ }
+
+ @Override
+ public void onFlick() {
+ sendRobotThisCommand(lexicon.explore());
+ }
+
+ @Override
+ public void onTwist() {
+ sendRobotThisCommand(lexicon.rotateRight());
+ }
+
+//These functions won't be called until you subscribe to the appropriate gestures
+//in a class that extends AbstractGestureClientActivity in a wear app.
+
+ @Override
+ public void onTiltX(float x) {
+ Log.e(TAG, "This function should not be called unless subscribed to TILT_X " + x);
+ if (x < 0){
+ sendRobotThisCommand(lexicon.turnLeft());
+ } else {
+ sendRobotThisCommand(lexicon.turnRight());
+ }
+// throw new IllegalStateException("This function should not be called unless subscribed to TILT_X.");
+ }
+
+ @Override
+ public void onTilt(float x, float y, float z) {
+ Log.e(TAG, "This function should not be called unless subscribed to onTilt." + x + " " + y + " " + z);
+ }
+
+ @Override
+ public void onWindowClosed() {
+ Log.e("MainWatchActivity","This function should not be called unless windowed gesture detection is enabled.");
+ }
+
+
+ public String sendRobotThisCommand(String command) {
+ String guessedCommand = lexicon.guessWhatToDo(command);
+ Toast.makeText(this, guessedCommand, Toast.LENGTH_SHORT).show();
+
+ if (Locale.getDefault().getLanguage().contains("fr")) {
+ mTts.speak(lexicon.FR_CARRIER_PHRASE + guessedCommand, TextToSpeech.QUEUE_ADD, null);
+ } else {
+ mTts.speak(lexicon.EN_CARRIER_PHRASE + guessedCommand, TextToSpeech.QUEUE_ADD, null);
+ }
+ return lexicon.executeGuess();
+ }
+
+ public void onCommandByVoiceClick(View v) {
+ promptTheUserToTalk();
+ startVoiceRecognitionActivity();
+ }
+
+ public void onViewGesturesClick(View v) {
+ Intent i = new Intent(this, GestureBuilderActivity.class);
+ startActivity(i);
+ }
+
+ public boolean isIntentAvailable(String action) {
+ final Intent intent = new Intent(action);
+ return isIntentAvailable(intent);
+ }
+
+ public boolean isIntentAvailable(final Intent intent) {
+ final PackageManager packageManager = this.getPackageManager();
+ List list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
+ return list.size() > 0;
+ }
+}
diff --git a/AndroidArduinoOpenCV/src/com/androidmontreal/arduino/bluetooth/BluetoothChatService.java b/Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/robots/BluetoothChatService.java
similarity index 56%
rename from AndroidArduinoOpenCV/src/com/androidmontreal/arduino/bluetooth/BluetoothChatService.java
rename to Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/robots/BluetoothChatService.java
index ba7a8f7..315875f 100644
--- a/AndroidArduinoOpenCV/src/com/androidmontreal/arduino/bluetooth/BluetoothChatService.java
+++ b/Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/robots/BluetoothChatService.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2009 The Android Open Source Project
+ * Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,12 +14,7 @@
* limitations under the License.
*/
-package com.androidmontreal.arduino.bluetooth;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.UUID;
+package com.androidmontreal.gesturevoicecommander.robots;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
@@ -31,51 +26,62 @@
import android.os.Message;
import android.util.Log;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.UUID;
+
/**
* This class does all the work for setting up and managing Bluetooth
- * connections with other devices. It has a thread that listens for incoming
- * connections, a thread for connecting with a device, and a thread for
- * performing data transmissions when connected.
+ * connections with other devices. It has a thread that listens for
+ * incoming connections, a thread for connecting with a device, and a
+ * thread for performing data transmissions when connected.
*/
public class BluetoothChatService {
// Debugging
private static final String TAG = "BluetoothChatService";
- private static final boolean D = true;
// Name for the SDP record when creating server socket
- private static final String NAME = "BluetoothChat";
+ private static final String NAME_SECURE = "BluetoothChatSecure";
+ private static final String NAME_INSECURE = "BluetoothChatInsecure";
// Unique UUID for this application
- private static final UUID MY_UUID = UUID
- .fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
-
- private static final UUID SERIAL_PORT_PROFILE_DEFAULT_UUID = UUID
- .fromString("00001101-0000-1000-8000-0005F9B34FB");
+ private static final UUID MY_UUID_SECURE =
+ UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
+ private static final UUID MY_UUID_INSECURE =
+ UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
// Member fields
private final BluetoothAdapter mAdapter;
private final Handler mHandler;
- private AcceptThread mAcceptThread;
+ private AcceptThread mSecureAcceptThread;
+ private AcceptThread mInsecureAcceptThread;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
private int mState;
// Constants that indicate the current connection state
- public static final int STATE_NONE = 0; // we're doing nothing
- public static final int STATE_LISTEN = 1; // now listening for incoming
- // connections
- public static final int STATE_CONNECTING = 2; // now initiating an outgoing
- // connection
- public static final int STATE_CONNECTED = 3; // now connected to a remote
- // device
+ public static final int STATE_NONE = 0; // we're doing nothing
+ public static final int STATE_LISTEN = 1; // now listening for incoming connections
+ public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
+ public static final int STATE_CONNECTED = 3; // now connected to a remote device
+
+ // Message types sent from the BluetoothChatService Handler
+ public static final int MESSAGE_STATE_CHANGE = 1;
+ public static final int MESSAGE_READ = 2;
+ public static final int MESSAGE_WRITE = 3;
+ public static final int MESSAGE_DEVICE_NAME = 4;
+ public static final int MESSAGE_TOAST = 5;
+
+ // Key names received from the BluetoothChatService Handler
+ public static final String DEVICE_NAME = "device_name";
+ public static final String TOAST = "toast";
/**
* Constructor. Prepares a new BluetoothChat session.
- *
- * @param context
- * The UI Activity Context
- * @param handler
- * A Handler to send messages back to the UI Activity
+ *
+ * @param context The UI Activity Context
+ * @param handler A Handler to send messages back to the UI Activity
*/
public BluetoothChatService(Context context, Handler handler) {
mAdapter = BluetoothAdapter.getDefaultAdapter();
@@ -85,18 +91,15 @@ public BluetoothChatService(Context context, Handler handler) {
/**
* Set the current state of the chat connection
- *
- * @param state
- * An integer defining the current connection state
+ *
+ * @param state An integer defining the current connection state
*/
private synchronized void setState(int state) {
- if (D)
- Log.d(TAG, "setState() " + mState + " -> " + state);
+ Log.d(TAG, "setState() " + mState + " -> " + state);
mState = state;
// Give the new state to the Handler so the UI Activity can update
- mHandler.obtainMessage(RoogleTank.MESSAGE_STATE_CHANGE, state, -1)
- .sendToTarget();
+ mHandler.obtainMessage(MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
}
/**
@@ -111,8 +114,7 @@ public synchronized int getState() {
* session in listening (server) mode. Called by the Activity onResume()
*/
public synchronized void start() {
- if (D)
- Log.d(TAG, "start");
+ Log.d(TAG, "start");
// Cancel any thread attempting to make a connection
if (mConnectThread != null) {
@@ -126,23 +128,27 @@ public synchronized void start() {
mConnectedThread = null;
}
+ setState(STATE_LISTEN);
+
// Start the thread to listen on a BluetoothServerSocket
- if (mAcceptThread == null) {
- mAcceptThread = new AcceptThread();
- mAcceptThread.start();
+ if (mSecureAcceptThread == null) {
+ mSecureAcceptThread = new AcceptThread(true);
+ mSecureAcceptThread.start();
+ }
+ if (mInsecureAcceptThread == null) {
+ mInsecureAcceptThread = new AcceptThread(false);
+ mInsecureAcceptThread.start();
}
- setState(STATE_LISTEN);
}
/**
* Start the ConnectThread to initiate a connection to a remote device.
- *
- * @param device
- * The BluetoothDevice to connect
+ *
+ * @param device The BluetoothDevice to connect
+ * @param secure Socket Security type - Secure (true) , Insecure (false)
*/
- public synchronized void connect(BluetoothDevice device) {
- if (D)
- Log.d(TAG, "connect to: " + device);
+ public synchronized void connect(BluetoothDevice device, boolean secure) {
+ Log.d(TAG, "connect to: " + device);
// Cancel any thread attempting to make a connection
if (mState == STATE_CONNECTING) {
@@ -159,23 +165,20 @@ public synchronized void connect(BluetoothDevice device) {
}
// Start the thread to connect with the given device
- mConnectThread = new ConnectThread(device);
+ mConnectThread = new ConnectThread(device, secure);
mConnectThread.start();
setState(STATE_CONNECTING);
}
/**
* Start the ConnectedThread to begin managing a Bluetooth connection
- *
- * @param socket
- * The BluetoothSocket on which the connection was made
- * @param device
- * The BluetoothDevice that has been connected
+ *
+ * @param socket The BluetoothSocket on which the connection was made
+ * @param device The BluetoothDevice that has been connected
*/
- public synchronized void connected(BluetoothSocket socket,
- BluetoothDevice device) {
- if (D)
- Log.d(TAG, "connected");
+ public synchronized void connected(BluetoothSocket socket, BluetoothDevice
+ device, final String socketType) {
+ Log.d(TAG, "connected, Socket Type:" + socketType);
// Cancel the thread that completed the connection
if (mConnectThread != null) {
@@ -189,21 +192,24 @@ public synchronized void connected(BluetoothSocket socket,
mConnectedThread = null;
}
- // Cancel the accept thread because we only want to connect to one
- // device
- if (mAcceptThread != null) {
- mAcceptThread.cancel();
- mAcceptThread = null;
+ // Cancel the accept thread because we only want to connect to one device
+ if (mSecureAcceptThread != null) {
+ mSecureAcceptThread.cancel();
+ mSecureAcceptThread = null;
+ }
+ if (mInsecureAcceptThread != null) {
+ mInsecureAcceptThread.cancel();
+ mInsecureAcceptThread = null;
}
// Start the thread to manage the connection and perform transmissions
- mConnectedThread = new ConnectedThread(socket);
+ mConnectedThread = new ConnectedThread(socket, socketType);
mConnectedThread.start();
// Send the name of the connected device back to the UI Activity
- Message msg = mHandler.obtainMessage(RoogleTank.MESSAGE_DEVICE_NAME);
+ Message msg = mHandler.obtainMessage(MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
- bundle.putString(RoogleTank.DEVICE_NAME, device.getName());
+ bundle.putString(DEVICE_NAME, device.getName());
msg.setData(bundle);
mHandler.sendMessage(msg);
@@ -214,28 +220,34 @@ public synchronized void connected(BluetoothSocket socket,
* Stop all threads
*/
public synchronized void stop() {
- if (D)
- Log.d(TAG, "stop");
+ Log.d(TAG, "stop");
+
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
+
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
- if (mAcceptThread != null) {
- mAcceptThread.cancel();
- mAcceptThread = null;
+
+ if (mSecureAcceptThread != null) {
+ mSecureAcceptThread.cancel();
+ mSecureAcceptThread = null;
+ }
+
+ if (mInsecureAcceptThread != null) {
+ mInsecureAcceptThread.cancel();
+ mInsecureAcceptThread = null;
}
setState(STATE_NONE);
}
/**
* Write to the ConnectedThread in an unsynchronized manner
- *
- * @param out
- * The bytes to write
+ *
+ * @param out The bytes to write
* @see ConnectedThread#write(byte[])
*/
public void write(byte[] out) {
@@ -243,8 +255,7 @@ public void write(byte[] out) {
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
- if (mState != STATE_CONNECTED)
- return;
+ if (mState != STATE_CONNECTED) return;
r = mConnectedThread;
}
// Perform the write unsynchronized
@@ -255,56 +266,66 @@ public void write(byte[] out) {
* Indicate that the connection attempt failed and notify the UI Activity.
*/
private void connectionFailed() {
- setState(STATE_LISTEN);
-
// Send a failure message back to the Activity
- Message msg = mHandler.obtainMessage(RoogleTank.MESSAGE_TOAST);
+ Message msg = mHandler.obtainMessage(MESSAGE_TOAST);
Bundle bundle = new Bundle();
- bundle.putString(RoogleTank.TOAST, "Unable to connect device");
+ bundle.putString(TOAST, "Unable to connect device");
msg.setData(bundle);
mHandler.sendMessage(msg);
+
+ // Start the service over to restart listening mode
+ BluetoothChatService.this.start();
}
/**
* Indicate that the connection was lost and notify the UI Activity.
*/
private void connectionLost() {
- setState(STATE_LISTEN);
-
// Send a failure message back to the Activity
- Message msg = mHandler.obtainMessage(RoogleTank.MESSAGE_TOAST);
+ Message msg = mHandler.obtainMessage(MESSAGE_TOAST);
Bundle bundle = new Bundle();
- bundle.putString(RoogleTank.TOAST, "Device connection was lost");
+ bundle.putString(TOAST, "Device connection was lost");
msg.setData(bundle);
mHandler.sendMessage(msg);
+
+ // Start the service over to restart listening mode
+ BluetoothChatService.this.start();
}
/**
* This thread runs while listening for incoming connections. It behaves
- * like a server-side client. It runs until a connection is accepted (or
- * until cancelled).
+ * like a server-side client. It runs until a connection is accepted
+ * (or until cancelled).
*/
private class AcceptThread extends Thread {
// The local server socket
private final BluetoothServerSocket mmServerSocket;
+ private String mSocketType;
- public AcceptThread() {
+ public AcceptThread(boolean secure) {
BluetoothServerSocket tmp = null;
+ mSocketType = secure ? "Secure" : "Insecure";
// Create a new listening server socket
try {
- tmp = mAdapter
- .listenUsingRfcommWithServiceRecord(NAME, SERIAL_PORT_PROFILE_DEFAULT_UUID);
+ if (secure) {
+ tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE,
+ MY_UUID_SECURE);
+ } else {
+ tmp = mAdapter.listenUsingInsecureRfcommWithServiceRecord(
+ NAME_INSECURE, MY_UUID_INSECURE);
+ }
} catch (IOException e) {
- Log.e(TAG, "listen() failed", e);
+ Log.e(TAG, "Socket Type: " + mSocketType + "listen() failed", e);
}
mmServerSocket = tmp;
}
public void run() {
- if (D)
- Log.d(TAG, "BEGIN mAcceptThread" + this);
- setName("AcceptThread");
+ Log.d(TAG, "Socket Type: " + mSocketType +
+ "BEGIN mAcceptThread" + this);
+ setName("AcceptThread" + mSocketType);
+
BluetoothSocket socket = null;
// Listen to the server socket if we're not connected
@@ -314,7 +335,8 @@ public void run() {
// successful connection or an exception
socket = mmServerSocket.accept();
} catch (IOException e) {
- Log.e(TAG, "accept() failed", e);
+ Log.e(TAG, "Socket Type: " + mSocketType + "accept() failed", e);
+ e.printStackTrace();
break;
}
@@ -322,66 +344,75 @@ public void run() {
if (socket != null) {
synchronized (BluetoothChatService.this) {
switch (mState) {
- case STATE_LISTEN:
- case STATE_CONNECTING:
- // Situation normal. Start the connected thread.
- connected(socket, socket.getRemoteDevice());
- break;
- case STATE_NONE:
- case STATE_CONNECTED:
- // Either not ready or already connected. Terminate
- // new socket.
- try {
- socket.close();
- } catch (IOException e) {
- Log.e(TAG, "Could not close unwanted socket", e);
- }
- break;
+ case STATE_LISTEN:
+ case STATE_CONNECTING:
+ // Situation normal. Start the connected thread.
+ connected(socket, socket.getRemoteDevice(),
+ mSocketType);
+ break;
+ case STATE_NONE:
+ case STATE_CONNECTED:
+ // Either not ready or already connected. Terminate new socket.
+ try {
+ socket.close();
+ } catch (IOException e) {
+ Log.e(TAG, "Could not close unwanted socket", e);
+ }
+ break;
}
}
}
}
- if (D)
- Log.i(TAG, "END mAcceptThread");
+ Log.i(TAG, "END mAcceptThread, socket Type: " + mSocketType);
+
}
public void cancel() {
- if (D)
- Log.d(TAG, "cancel " + this);
+ Log.d(TAG, "Socket Type" + mSocketType + "cancel " + this);
try {
mmServerSocket.close();
} catch (IOException e) {
- Log.e(TAG, "close() of server failed", e);
+ Log.e(TAG, "Socket Type" + mSocketType + "close() of server failed", e);
}
}
}
+
/**
- * This thread runs while attempting to make an outgoing connection with a
- * device. It runs straight through; the connection either succeeds or
- * fails.
+ * This thread runs while attempting to make an outgoing connection
+ * with a device. It runs straight through; the connection either
+ * succeeds or fails.
*/
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
+ private String mSocketType;
- public ConnectThread(BluetoothDevice device) {
+ public ConnectThread(BluetoothDevice device, boolean secure) {
mmDevice = device;
BluetoothSocket tmp = null;
+ mSocketType = secure ? "Secure" : "Insecure";
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
- tmp = device.createRfcommSocketToServiceRecord(SERIAL_PORT_PROFILE_DEFAULT_UUID);
+ if (secure) {
+ tmp = device.createRfcommSocketToServiceRecord(
+ MY_UUID_SECURE);
+ } else {
+ tmp = device.createInsecureRfcommSocketToServiceRecord(
+ MY_UUID_INSECURE);
+ }
} catch (IOException e) {
- Log.e(TAG, "create() failed", e);
+ Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
+ e.printStackTrace();
}
mmSocket = tmp;
}
public void run() {
- Log.i(TAG, "BEGIN mConnectThread");
- setName("ConnectThread");
+ Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType);
+ setName("ConnectThread" + mSocketType);
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
@@ -392,17 +423,17 @@ public void run() {
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
- connectionFailed();
+ Log.d(TAG, "exception when trying to connect");
+ e.printStackTrace();
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
- Log.e(TAG,
- "unable to close() socket during connection failure",
- e2);
+ Log.e(TAG, "unable to close() " + mSocketType +
+ " socket during connection failure", e2);
+ e2.printStackTrace();
}
- // Start the service over to restart listening mode
- BluetoothChatService.this.start();
+ connectionFailed();
return;
}
@@ -412,29 +443,29 @@ public void run() {
}
// Start the connected thread
- connected(mmSocket, mmDevice);
+ connected(mmSocket, mmDevice, mSocketType);
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
- Log.e(TAG, "close() of connect socket failed", e);
+ Log.e(TAG, "close() of connect " + mSocketType + " socket failed", e);
}
}
}
/**
- * This thread runs during a connection with a remote device. It handles all
- * incoming and outgoing transmissions.
+ * This thread runs during a connection with a remote device.
+ * It handles all incoming and outgoing transmissions.
*/
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
- public ConnectedThread(BluetoothSocket socket) {
- Log.d(TAG, "create ConnectedThread");
+ public ConnectedThread(BluetoothSocket socket, String socketType) {
+ Log.d(TAG, "create ConnectedThread: " + socketType);
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
@@ -463,11 +494,13 @@ public void run() {
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
- mHandler.obtainMessage(RoogleTank.MESSAGE_READ, bytes,
- -1, buffer).sendToTarget();
+ mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
+ .sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
+ // Start the service over to restart listening mode
+ BluetoothChatService.this.start();
break;
}
}
@@ -475,17 +508,16 @@ public void run() {
/**
* Write to the connected OutStream.
- *
- * @param buffer
- * The bytes to write
+ *
+ * @param buffer The bytes to write
*/
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
- mHandler.obtainMessage(RoogleTank.MESSAGE_WRITE, -1, -1,
- buffer).sendToTarget();
+ mHandler.obtainMessage(MESSAGE_WRITE, -1, -1, buffer)
+ .sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
diff --git a/AndroidArduinoOpenCV/src/com/androidmontreal/arduino/bluetooth/DeviceListActivity.java b/Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/robots/DeviceListActivity.java
similarity index 69%
rename from AndroidArduinoOpenCV/src/com/androidmontreal/arduino/bluetooth/DeviceListActivity.java
rename to Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/robots/DeviceListActivity.java
index 31cec9b..bd74255 100644
--- a/AndroidArduinoOpenCV/src/com/androidmontreal/arduino/bluetooth/DeviceListActivity.java
+++ b/Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/robots/DeviceListActivity.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2009 The Android Open Source Project
+ * Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,9 +14,7 @@
* limitations under the License.
*/
-package com.androidmontreal.arduino.bluetooth;
-
-import java.util.Set;
+package com.androidmontreal.gesturevoicecommander.robots;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
@@ -29,15 +27,16 @@
import android.util.Log;
import android.view.View;
import android.view.Window;
-import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
-import android.widget.AdapterView.OnItemClickListener;
+import android.widget.Toast;
+
+import com.androidmontreal.gesturevoicecommander.R;
-import com.androidmontreal.opencv.R;
+import java.util.Set;
/**
* This Activity appears as a dialog. It lists any paired devices and
@@ -46,16 +45,30 @@
* Activity in the result Intent.
*/
public class DeviceListActivity extends Activity {
- // Debugging
+
+ /**
+ * Tag for Log
+ */
private static final String TAG = "DeviceListActivity";
- private static final boolean D = true;
- // Return Intent extra
+ /**
+ * Request codes
+ */
+ private static final int REQUEST_ENABLE_BT = 9234;
+
+ /**
+ * Return Intent extra
+ */
public static String EXTRA_DEVICE_ADDRESS = "device_address";
- // Member fields
+ /**
+ * Member fields
+ */
private BluetoothAdapter mBtAdapter;
- private ArrayAdapter mPairedDevicesArrayAdapter;
+
+ /**
+ * Newly discovered devices
+ */
private ArrayAdapter mNewDevicesArrayAdapter;
@Override
@@ -64,14 +77,27 @@ protected void onCreate(Bundle savedInstanceState) {
// Setup the window
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
- setContentView(R.layout.device_list);
+ setContentView(R.layout.activity_device_list);
+ }
- // Set result CANCELED incase the user backs out
+ @Override
+ protected void onResume() {
+ super.onResume();
+
+ // Set result CANCELED in case the user backs out
setResult(Activity.RESULT_CANCELED);
+ // Get the local Bluetooth adapter
+ mBtAdapter = BluetoothAdapter.getDefaultAdapter();
+ if (mBtAdapter == null){
+ blueToothIsNotSupported();
+ return;
+ }
+ requestBluetooth();
+
// Initialize the button to perform device discovery
Button scanButton = (Button) findViewById(R.id.button_scan);
- scanButton.setOnClickListener(new OnClickListener() {
+ scanButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
doDiscovery();
v.setVisibility(View.GONE);
@@ -80,12 +106,13 @@ public void onClick(View v) {
// Initialize array adapters. One for already paired devices and
// one for newly discovered devices
- mPairedDevicesArrayAdapter = new ArrayAdapter(this, R.layout.device_name);
+ ArrayAdapter pairedDevicesArrayAdapter =
+ new ArrayAdapter(this, R.layout.device_name);
mNewDevicesArrayAdapter = new ArrayAdapter(this, R.layout.device_name);
// Find and set up the ListView for paired devices
ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
- pairedListView.setAdapter(mPairedDevicesArrayAdapter);
+ pairedListView.setAdapter(pairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(mDeviceClickListener);
// Find and set up the ListView for newly discovered devices
@@ -101,9 +128,6 @@ public void onClick(View v) {
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
- // Get the local Bluetooth adapter
- mBtAdapter = BluetoothAdapter.getDefaultAdapter();
-
// Get a set of currently paired devices
Set pairedDevices = mBtAdapter.getBondedDevices();
@@ -111,14 +135,26 @@ public void onClick(View v) {
if (pairedDevices.size() > 0) {
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice device : pairedDevices) {
- mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
+ pairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
- String noDevices = getResources().getText(R.string.none_paired).toString();
- mPairedDevicesArrayAdapter.add(noDevices);
+ String noDevices = getResources().getText(R.string.bluetooth_none_paired).toString();
+ pairedDevicesArrayAdapter.add(noDevices);
+ }
+ }
+
+ public void requestBluetooth(){
+ if (!mBtAdapter.isEnabled()) {
+ Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
+ startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
+ public void blueToothIsNotSupported(){
+ Toast.makeText(this, R.string.bluetooth_not_supported, Toast.LENGTH_SHORT).show();
+ finish();
+ }
+
@Override
protected void onDestroy() {
super.onDestroy();
@@ -132,11 +168,33 @@ protected void onDestroy() {
this.unregisterReceiver(mReceiver);
}
+ @Override
+ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+ super.onActivityResult(requestCode, resultCode, data);
+
+ switch (requestCode) {
+
+ case REQUEST_ENABLE_BT:
+ if (resultCode != Activity.RESULT_OK || resultCode == Activity.RESULT_CANCELED) {
+ Toast.makeText(this, R.string.bluetooth_not_enabled_leaving, Toast.LENGTH_SHORT).show();
+ finish();
+ } else {
+ // Can use bluetooth
+ }
+ break;
+ }
+ }
+
/**
* Start device discover with the BluetoothAdapter
*/
private void doDiscovery() {
- if (D) Log.d(TAG, "doDiscovery()");
+ Log.d(TAG, "doDiscovery()");
+
+ if (mBtAdapter == null) {
+ finish();
+ return;
+ }
// Indicate scanning in the title
setProgressBarIndeterminateVisibility(true);
@@ -154,8 +212,11 @@ private void doDiscovery() {
mBtAdapter.startDiscovery();
}
- // The on-click listener for all devices in the ListViews
- private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
+ /**
+ * The on-click listener for all devices in the ListViews
+ */
+ private AdapterView.OnItemClickListener mDeviceClickListener
+ = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
mBtAdapter.cancelDiscovery();
@@ -174,8 +235,10 @@ public void onItemClick(AdapterView> av, View v, int arg2, long arg3) {
}
};
- // The BroadcastReceiver that listens for discovered devices and
- // changes the title when discovery is finished
+ /**
+ * The BroadcastReceiver that listens for discovered devices and changes the title when
+ * discovery is finished
+ */
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
@@ -189,16 +252,16 @@ public void onReceive(Context context, Intent intent) {
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
- // When discovery is finished, change the Activity title
+ // When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle(R.string.select_device);
if (mNewDevicesArrayAdapter.getCount() == 0) {
- String noDevices = getResources().getText(R.string.none_found).toString();
+ String noDevices = getResources().getText(R.string.bluetooth_none_found).toString();
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
-}
+}
\ No newline at end of file
diff --git a/Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/robots/Lexicon.java b/Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/robots/Lexicon.java
new file mode 100644
index 0000000..ebad7c5
--- /dev/null
+++ b/Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/robots/Lexicon.java
@@ -0,0 +1,204 @@
+package com.androidmontreal.gesturevoicecommander.robots;
+
+import android.content.Intent;
+
+import java.util.ArrayList;
+import java.util.Locale;
+
+public class Lexicon {
+ private int language;
+ private int timer = 5;
+
+ /*
+ * Languages
+ */
+ public static final int EN = 1000;
+ public static final int FR = 1001;
+ public static final String EN_CARRIER_PHRASE = "I will tell the robot: ";
+ public static final String FR_CARRIER_PHRASE = "Je vais dire au robo: ";
+
+ /*
+ * Commands, use the order of these constants for the precedence order of the
+ * commands (STOP has the highest precedence)
+ */
+ public static final int STOP = 0;
+ public static final int EXPLORE = 1;
+ public static final int FORWARD = 2;
+ public static final int REVERSE = 3;
+ public static final int ROTATERIGHT = 4;
+ public static final int ROTATELEFT = 5;
+ public static final int TURNRIGHT = 6;
+ public static final int TURNLEFT = 7;
+ public static final int CONNECT = 8;
+
+ private ArrayList en;
+ private ArrayList fr;
+
+ private int mCommandToExecute;
+
+ public String stop() {
+ return "S";
+ }
+
+ public String explore() {
+ return "E";
+ }
+
+ public String forward() {
+ return "1F2F";
+ }
+
+ public String reverse() {
+ return "1R2R";
+ }
+
+ public String turnRight() {
+ return "1F";
+ }
+
+ public String turnLeft() {
+ return "2F";
+ }
+
+ public String rotateRight() {
+ return "1F2R";
+ }
+
+ public String rotateLeft() {
+ return "1R2F";
+ }
+
+ public String connect() {
+ return "CONNECT";
+ }
+
+ public void defineLanguages() {
+ en = new ArrayList();
+ en.add(STOP, "stop:wait:don't:no:damn");
+ en.add(EXPLORE, "explore:try");
+ en.add(FORWARD, "forward:ahead");
+ en.add(REVERSE, "reverse:back");
+ en.add(ROTATERIGHT, "rotate&right");
+ en.add(ROTATELEFT, "rotate&left");
+ en.add(TURNRIGHT, "right");
+ en.add(TURNLEFT, "left");
+ en.add(CONNECT, "connect:body:robot:bluetooth");
+
+ fr = new ArrayList();
+ fr.add(STOP, "arrête:arrêter:arrêté:arrêter:arrêtez:pas:voyons:voyant:m****:merde:zut:non:stop");
+ fr.add(EXPLORE, "explore:explorer");
+ fr.add(FORWARD, "avance:tu dois:tu dois:te doi:tournoi:tout droit:avanc:forward");
+ fr.add(REVERSE, "recule:recul:reverse:arrière");
+ fr.add(ROTATERIGHT, "pivoter vers la droite:vers la droite:pilot:pivot:rotate&droit");
+ fr.add(ROTATELEFT, "pivoter vers la gauche:vers la gauche:rotate&gauche");
+ fr.add(TURNRIGHT, "à la droite:droite:droit:right");
+ fr.add(TURNLEFT, "à la gauche:gauche:left");
+ fr.add(CONNECT, "connecter:mon corps:robot:bluetooth");
+ }
+
+ public String execute(int commandInteger) {
+ switch (commandInteger) {
+ case CONNECT:
+ return connect();
+ case STOP:
+ return stop();
+ case EXPLORE:
+ return explore();
+ case FORWARD:
+ return forward();
+ case REVERSE:
+ return reverse();
+ case TURNRIGHT:
+ return turnRight();
+ case TURNLEFT:
+ return turnLeft();
+ case ROTATERIGHT:
+ return rotateRight();
+ case ROTATELEFT:
+ return rotateLeft();
+ default:
+ return stop();
+ }
+ }
+
+ public String guessWhatToDo(String command) {
+ command = command.toLowerCase();
+ int commandToExecute = STOP;
+ String commandForHumans = command;
+
+ ArrayList humancommands = en;
+ if (language == FR) {
+ humancommands = fr;
+ }
+ for (int i = 0; i < humancommands.size(); i++) {
+ String[] andwords = humancommands.get(i).split("&");
+ String[] orwords = humancommands.get(i).split(":");
+ /*
+ * If there are AND words, then check first to see if it matches all words
+ */
+ if (andwords.length > 1) {
+ int wordsfound = 0;
+ commandForHumans = andwords[0];
+ for (int k = 0; k < andwords.length; k++) {
+ if (command.contains(andwords[k])) {
+ wordsfound++;
+ }
+ }
+ if (wordsfound >= andwords.length) {
+ commandToExecute = i;
+ mCommandToExecute = commandToExecute;
+ return commandForHumans;
+ }
+ }
+ /*
+ * Then if a command hasn't been issued, check for the OR words.
+ */
+ if (orwords.length > 0) {
+ commandForHumans = orwords[0];
+ for (int k = 0; k < orwords.length; k++) {
+ if (command.contains(orwords[k])) {
+ commandToExecute = i;
+ mCommandToExecute = commandToExecute;
+ return commandForHumans;
+ }
+ }
+ }
+
+ }
+ mCommandToExecute = commandToExecute;
+ return commandForHumans;
+ }
+
+ public String executeGuess() {
+ if (mCommandToExecute >= 0) {
+ return execute(mCommandToExecute);
+ }
+ return "";
+ }
+
+ public Lexicon(int language, int timer) {
+ super();
+ defineLanguages();
+ this.language = language;
+ this.timer = timer;
+ }
+
+ public Lexicon(int language) {
+ super();
+ defineLanguages();
+ this.language = language;
+ this.timer = 5;
+ }
+
+ public Lexicon() {
+ super();
+ defineLanguages();
+ if (Locale.getDefault().getLanguage().contains("fr")) {
+ this.language = FR;
+ } else {
+ this.language = EN;
+ }
+ this.timer = 5;
+ }
+
+}
diff --git a/Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/robots/Robot.java b/Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/robots/Robot.java
new file mode 100644
index 0000000..73bf2dd
--- /dev/null
+++ b/Tutorial/app/src/main/java/com/androidmontreal/gesturevoicecommander/robots/Robot.java
@@ -0,0 +1,341 @@
+package com.androidmontreal.gesturevoicecommander.robots;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+
+import android.app.Activity;
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothDevice;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.gesture.Gesture;
+import android.gesture.GestureLibraries;
+import android.gesture.GestureLibrary;
+import android.gesture.GestureOverlayView;
+import android.gesture.Prediction;
+import android.gesture.GestureOverlayView.OnGesturePerformedListener;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.speech.RecognizerIntent;
+import android.speech.tts.TextToSpeech;
+import android.speech.tts.TextToSpeech.OnInitListener;
+import android.util.Log;
+import android.view.View;
+import android.widget.Toast;
+
+import com.androidmontreal.gesturevoicecommander.GestureBuilderActivity;
+import com.androidmontreal.gesturevoicecommander.R;
+
+/**
+ * Building on what we saw in MakeItUnderstand, now lets make it perform
+ * actions. Here is some super simple code that builds on the BluetoothChat
+ * sample code to send meassages to a bluetooth device/robot.
+ *
+ * @author cesine
+ */
+public class Robot extends Activity implements OnInitListener, OnGesturePerformedListener {
+ private static final String TAG = "Robot";
+ private static final int RETURN_FROM_VOICE_RECOGNITION_REQUEST_CODE = 341;
+ public static final int REQUEST_CONNECT_DEVICE = 8888;
+
+ private static final boolean D = true;
+
+ /**
+ * Talk to the user
+ */
+ private TextToSpeech mTts;
+
+ /*
+ * A gesture library we created with the GestureBuilder, saved on the SDCard
+ * and then imported into the res/raw folder of this project
+ */
+ private GestureLibrary gestureLib;
+
+ /* A little lexicon we made for the DFR Rover at Cloud Robotics Hackathon */
+ private Lexicon lexicon;
+
+ /* A re-executable sequence of commands in time */
+ private HashMap mCommandMemory;
+
+ /* Message passing to an actual bluetooth device/robot */
+ private BluetoothAdapter mBluetoothAdapter = null;
+ private BluetoothChatService mChatService;
+ private String mConnectedDeviceName = "";
+ private static final boolean SECURE_CONNECTION = true;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+
+ mTts = new TextToSpeech(this, this);
+
+ GestureOverlayView gestureOverlayView = new GestureOverlayView(this);
+ View inflate = getLayoutInflater().inflate(R.layout.commander, null);
+ gestureOverlayView.addView(inflate);
+ gestureOverlayView.addOnGesturePerformedListener(this);
+ // gestureLib = GestureLibraries.fromFile(fileOnYourSDCard);
+ gestureLib = GestureLibraries.fromRawResource(this, R.raw.gestures);
+ if (!gestureLib.load()) {
+ Toast.makeText(this, R.string.gestures_empty, Toast.LENGTH_SHORT).show();
+ finish();
+ }
+ setContentView(gestureOverlayView);
+
+ lexicon = new Lexicon();
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+
+ if (mCommandMemory == null) {
+ mCommandMemory = new HashMap();
+ }
+
+ if (mChatService != null) {
+ // Only if the state is STATE_NONE, do we know that we haven't started already
+ if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
+ // Start the Bluetooth chat services
+ mChatService.start();
+ }
+ }
+ }
+
+ protected void promptTheUserToTalk() {
+ if (isIntentAvailable(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)) {
+ this.speak(getString(R.string.im_listening));
+ } else {
+ this.speak(getString(R.string.i_cant_listen));
+ }
+ }
+
+ /**
+ * Fire an intent to start the voice recognition activity.
+ */
+ private void startVoiceRecognitionActivity() {
+ Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
+ intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
+ intent.putExtra(RecognizerIntent.EXTRA_PROMPT, getString(R.string.im_listening));
+ if (isIntentAvailable(intent)) {
+ startActivityForResult(intent, RETURN_FROM_VOICE_RECOGNITION_REQUEST_CODE);
+ } else {
+ Log.w(TAG, "This device doesn't have speech recognition, maybe its an emulator or a phone from china without google products?");
+ }
+ }
+
+ /**
+ * Handle the results from the voice recognition activity.
+ */
+ @Override
+ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+ super.onActivityResult(requestCode, resultCode, data);
+
+ switch (requestCode) {
+ case RETURN_FROM_VOICE_RECOGNITION_REQUEST_CODE:
+ if (resultCode == RESULT_OK) {
+ ArrayList matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
+ /* try to find a robot command in the first match */
+ if (matches.size() > 0) {
+ sendRobotThisCommand(matches.get(0));
+ }
+ }
+ break;
+ case REQUEST_CONNECT_DEVICE:
+ // When DeviceListActivity returns with a device to connect
+ if (resultCode == Activity.RESULT_OK) {
+ if (mChatService == null) {
+ mChatService = new BluetoothChatService(this, mHandler);
+ }
+ connectDevice(data);
+ }
+ break;
+ }
+ }
+
+ @Override
+ protected void onDestroy() {
+ if (mTts != null) {
+ mTts.stop();
+ mTts.shutdown();
+ }
+
+ if (mChatService != null) {
+ mChatService.stop();
+ }
+
+ super.onDestroy();
+ }
+
+ @Override
+ public void onInit(int status) {
+ if (status == TextToSpeech.SUCCESS) {
+ int result = mTts.setLanguage(Locale.getDefault());
+ if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
+ Log.e(TAG, "Language is not available.");
+ Toast.makeText(this,
+ "The " + Locale.getDefault().getDisplayLanguage()
+ + " TextToSpeech isn't installed, you can go into the "
+ + "\nAndroid's settings in the "
+ + "\nVoice Input and Output menu to turn it on. ",
+ Toast.LENGTH_LONG).show();
+ } else {
+ // everything is working.
+ this.speak(getString(R.string.instructions_to_look_at_menu));
+ }
+ } else {
+ Toast.makeText(this, "Sorry, I can't talk to you because " +
+ "I could not initialize TextToSpeech.", Toast.LENGTH_LONG).show();
+ }
+ }
+
+ public boolean speak(String message) {
+ if (mTts != null) {
+ mTts.speak(message, TextToSpeech.QUEUE_ADD, null);
+ } else {
+ Toast.makeText(this, "Sorry, I can't speak to you: " + message, Toast.LENGTH_LONG).show();
+ }
+ return true;
+ }
+
+ @Override
+ public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
+ ArrayList predictions = gestureLib.recognize(gesture);
+ for (Prediction prediction : predictions) {
+ if (prediction.score > 3.0) {
+ Log.d(TAG, "Detected this gesture " + prediction.name + " with a score of " + prediction.score);
+ }
+ }
+ if (predictions.size() > 0) {
+ sendRobotThisCommand(predictions.get(0).name);
+ }
+ }
+
+ /**
+ * Establish connection with a physical device/body via bluetooth
+ *
+ * @param data An {@link Intent} with {@link DeviceListActivity#EXTRA_DEVICE_ADDRESS} extra.
+ */
+ private void connectDevice(Intent data) {
+ // Get the device MAC address
+ String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
+ // Get the BluetoothDevice object
+ if (mBluetoothAdapter == null) {
+ mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
+ }
+ BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
+ // Attempt to connect to the device
+ mChatService.connect(device, SECURE_CONNECTION);
+ }
+
+ public String sendRobotThisCommand(String requestedCommand) {
+ String understoodCommand = lexicon.guessWhatToDo(requestedCommand);
+
+ // communicate understood command
+ Toast.makeText(this, understoodCommand, Toast.LENGTH_SHORT).show();
+ if (Locale.getDefault().getLanguage().contains("fr")) {
+ mTts.speak(lexicon.FR_CARRIER_PHRASE + understoodCommand, TextToSpeech.QUEUE_ADD, null);
+ } else {
+ mTts.speak(lexicon.EN_CARRIER_PHRASE + understoodCommand, TextToSpeech.QUEUE_ADD, null);
+ }
+
+ // remember understood command
+ mCommandMemory.put(System.currentTimeMillis(), "I want to: " + understoodCommand);
+
+ // translate into body commands
+ String bodyCommand = lexicon.executeGuess();
+ if ("CONNECT".equals(bodyCommand)) {
+ Intent serverIntent = new Intent(this, DeviceListActivity.class);
+ startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
+ return "";
+ }
+ if (mChatService != null){
+ // Check that we're actually connected before trying anything
+ if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
+ Toast.makeText(this, R.string.bluetooth_not_connected, Toast.LENGTH_SHORT).show();
+ return understoodCommand;
+ }
+ // Check that there's actually something to send
+ if (bodyCommand.length() > 0) {
+ // Get the message bytes and tell the BluetoothChatService to write
+ byte[] send = bodyCommand.getBytes();
+ mChatService.write(send);
+ }
+ }
+
+ return understoodCommand;
+ }
+
+ /**
+ * The Handler that gets information back from the BluetoothChatService
+ */
+ private final Handler mHandler = new Handler() {
+ @Override
+ public void handleMessage(Message msg) {
+ switch (msg.what) {
+ case BluetoothChatService.MESSAGE_STATE_CHANGE:
+ switch (msg.arg1) {
+ case BluetoothChatService.STATE_CONNECTED:
+ Log.d(TAG, getString(R.string.title_connected_to, mConnectedDeviceName));
+ break;
+ case BluetoothChatService.STATE_CONNECTING:
+ Log.d(TAG, "title_connecting");
+ break;
+ case BluetoothChatService.STATE_LISTEN:
+ break;
+ case BluetoothChatService.STATE_NONE:
+ Log.d(TAG, "title_not_connected");
+ break;
+ }
+ break;
+ case BluetoothChatService.MESSAGE_WRITE:
+ byte[] writeBuf = (byte[]) msg.obj;
+ // construct a string from the buffer
+ String bodyCommand = new String(writeBuf);
+ mCommandMemory.put(System.currentTimeMillis(), "I told my body to: " + bodyCommand);
+ break;
+ case BluetoothChatService.MESSAGE_READ:
+ byte[] readBuf = (byte[]) msg.obj;
+ // construct a string from the valid bytes in the buffer
+ String readMessage = new String(readBuf, 0, msg.arg1);
+ speak(readMessage);
+ mCommandMemory.put(System.currentTimeMillis(), "My body did: " + readMessage);
+ break;
+ case BluetoothChatService.MESSAGE_DEVICE_NAME:
+ // save the connected device's name
+ mConnectedDeviceName = msg.getData().getString(BluetoothChatService.DEVICE_NAME);
+ Toast.makeText(getApplicationContext(), "My body is: "
+ + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
+ break;
+ case BluetoothChatService.MESSAGE_TOAST:
+ Toast.makeText(getApplicationContext(), msg.getData().getString(BluetoothChatService.TOAST),
+ Toast.LENGTH_SHORT).show();
+ break;
+ }
+ }
+ };
+
+ public void onCommandByVoiceClick(View v) {
+ promptTheUserToTalk();
+ startVoiceRecognitionActivity();
+ }
+
+ public void onViewGesturesClick(View v) {
+ Intent i = new Intent(this, GestureBuilderActivity.class);
+ startActivity(i);
+ }
+
+ public boolean isIntentAvailable(String action) {
+ final Intent intent = new Intent(action);
+ return isIntentAvailable(intent);
+ }
+
+ public boolean isIntentAvailable(final Intent intent) {
+ final PackageManager packageManager = this.getPackageManager();
+ List list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
+ return list.size() > 0;
+ }
+}
diff --git a/GestureVoiceCommander/res/drawable-hdpi/app_icon.png b/Tutorial/app/src/main/res/drawable-hdpi/ic_launcher.png
similarity index 99%
rename from GestureVoiceCommander/res/drawable-hdpi/app_icon.png
rename to Tutorial/app/src/main/res/drawable-hdpi/ic_launcher.png
index c609872..d62b72a 100644
Binary files a/GestureVoiceCommander/res/drawable-hdpi/app_icon.png and b/Tutorial/app/src/main/res/drawable-hdpi/ic_launcher.png differ
diff --git a/GestureVoiceCommander/res/drawable-ldpi/ic_launcher.png b/Tutorial/app/src/main/res/drawable-ldpi/ic_launcher.png
similarity index 100%
rename from GestureVoiceCommander/res/drawable-ldpi/ic_launcher.png
rename to Tutorial/app/src/main/res/drawable-ldpi/ic_launcher.png
diff --git a/GestureVoiceCommander/res/drawable-mdpi/ic_launcher.png b/Tutorial/app/src/main/res/drawable-mdpi/ic_launcher.png
similarity index 100%
rename from GestureVoiceCommander/res/drawable-mdpi/ic_launcher.png
rename to Tutorial/app/src/main/res/drawable-mdpi/ic_launcher.png
diff --git a/AndroidArduinoOpenCV/res/layout/device_list.xml b/Tutorial/app/src/main/res/layout/activity_device_list.xml
similarity index 82%
rename from AndroidArduinoOpenCV/res/layout/device_list.xml
rename to Tutorial/app/src/main/res/layout/activity_device_list.xml
index 395695f..576f7fa 100644
--- a/AndroidArduinoOpenCV/res/layout/device_list.xml
+++ b/Tutorial/app/src/main/res/layout/activity_device_list.xml
@@ -1,5 +1,5 @@
-
-
-
+
+
-
+
+
-
+
+
-
+
+
+ />
\ No newline at end of file
diff --git a/Tutorial/res/layout/commander.xml b/Tutorial/app/src/main/res/layout/commander.xml
similarity index 100%
rename from Tutorial/res/layout/commander.xml
rename to Tutorial/app/src/main/res/layout/commander.xml
diff --git a/Tutorial/res/layout/create_gesture.xml b/Tutorial/app/src/main/res/layout/create_gesture.xml
similarity index 100%
rename from Tutorial/res/layout/create_gesture.xml
rename to Tutorial/app/src/main/res/layout/create_gesture.xml
diff --git a/AndroidArduinoOpenCV/res/layout/device_name.xml b/Tutorial/app/src/main/res/layout/device_name.xml
similarity index 92%
rename from AndroidArduinoOpenCV/res/layout/device_name.xml
rename to Tutorial/app/src/main/res/layout/device_name.xml
index 8fa358c..3e10a2d 100644
--- a/AndroidArduinoOpenCV/res/layout/device_name.xml
+++ b/Tutorial/app/src/main/res/layout/device_name.xml
@@ -1,5 +1,5 @@
-
- UpAndRunningWithAndroid
+ ControllerCreate a gestureI can talk! After all, I have speakers.Talk to me, I\'m listening...
+ I\'m sorry, your device is strange. It cannot recognize speech. You will have to use the gesture commands instead...I might have heard: Or maybe this: . I\'m pretty funny, ey? There were some other options, but I think I\'ll stop there.
+ Hi! The menu shows the list of commands you can use (you can speak, or draw).
@@ -75,4 +77,25 @@
Could not load %s. Make sure you have storage available.
-
\ No newline at end of file
+
+ Send
+ This device does not support bluetooth.
+ You are not connected to a device.
+ Bluetooth was not enabled. You won\'t be able to use the bluetooth functionality of this app.
+ Connecting...
+ Connected:
+ Not connected.
+
+
+ Scanning for devices...
+ Select a device to connect
+ No devices have been paired
+ No devices found
+ Paired Devices
+ Other Available Devices
+ Scan for devices
+
+
+ Connect a device
+ Make discoverable
+
diff --git a/Tutorial/build.gradle b/Tutorial/build.gradle
new file mode 100644
index 0000000..6a5c233
--- /dev/null
+++ b/Tutorial/build.gradle
@@ -0,0 +1,15 @@
+// Top-level build file where you can add configuration options common to all sub-projects/modules.
+buildscript {
+ repositories {
+ jcenter()
+ }
+ dependencies {
+ classpath 'com.android.tools.build:gradle:1.3.0'
+ }
+}
+
+allprojects {
+ repositories {
+ jcenter()
+ }
+}
diff --git a/Tutorial/gradle/wrapper/gradle-wrapper.properties b/Tutorial/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..0c71e76
--- /dev/null
+++ b/Tutorial/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+#Wed Apr 10 15:27:10 PDT 2013
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip
diff --git a/Tutorial/gradlew b/Tutorial/gradlew
new file mode 100755
index 0000000..91a7e26
--- /dev/null
+++ b/Tutorial/gradlew
@@ -0,0 +1,164 @@
+#!/usr/bin/env bash
+
+##############################################################################
+##
+## Gradle start up script for UN*X
+##
+##############################################################################
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn ( ) {
+ echo "$*"
+}
+
+die ( ) {
+ echo
+ echo "$*"
+ echo
+ exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+case "`uname`" in
+ CYGWIN* )
+ cygwin=true
+ ;;
+ Darwin* )
+ darwin=true
+ ;;
+ MINGW* )
+ msys=true
+ ;;
+esac
+
+# For Cygwin, ensure paths are in UNIX format before anything is touched.
+if $cygwin ; then
+ [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
+fi
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG=`dirname "$PRG"`"/$link"
+ fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >&-
+APP_HOME="`pwd -P`"
+cd "$SAVED" >&-
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD="java"
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
+ MAX_FD_LIMIT=`ulimit -H -n`
+ if [ $? -eq 0 ] ; then
+ if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+ MAX_FD="$MAX_FD_LIMIT"
+ fi
+ ulimit -n $MAX_FD
+ if [ $? -ne 0 ] ; then
+ warn "Could not set maximum file descriptor limit: $MAX_FD"
+ fi
+ else
+ warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+ fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+ GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+ APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+ CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+
+ # We build the pattern for arguments to be converted via cygpath
+ ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+ SEP=""
+ for dir in $ROOTDIRSRAW ; do
+ ROOTDIRS="$ROOTDIRS$SEP$dir"
+ SEP="|"
+ done
+ OURCYGPATTERN="(^($ROOTDIRS))"
+ # Add a user-defined pattern to the cygpath arguments
+ if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+ OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+ fi
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ i=0
+ for arg in "$@" ; do
+ CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+ CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
+
+ if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
+ eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+ else
+ eval `echo args$i`="\"$arg\""
+ fi
+ i=$((i+1))
+ done
+ case $i in
+ (0) set -- ;;
+ (1) set -- "$args0" ;;
+ (2) set -- "$args0" "$args1" ;;
+ (3) set -- "$args0" "$args1" "$args2" ;;
+ (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+ (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+ (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+ (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+ (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+ (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+ esac
+fi
+
+# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
+function splitJvmOpts() {
+ JVM_OPTS=("$@")
+}
+eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
+JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
+
+exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
diff --git a/Tutorial/gradlew.bat b/Tutorial/gradlew.bat
new file mode 100644
index 0000000..aec9973
--- /dev/null
+++ b/Tutorial/gradlew.bat
@@ -0,0 +1,90 @@
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS=
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto init
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto init
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:init
+@rem Get command-line arguments, handling Windowz variants
+
+if not "%OS%" == "Windows_NT" goto win9xME_args
+if "%@eval[2+2]" == "4" goto 4NT_args
+
+:win9xME_args
+@rem Slurp the command line arguments.
+set CMD_LINE_ARGS=
+set _SKIP=2
+
+:win9xME_args_slurp
+if "x%~1" == "x" goto execute
+
+set CMD_LINE_ARGS=%*
+goto execute
+
+:4NT_args
+@rem Get arguments from the 4NT Shell from JP Software
+set CMD_LINE_ARGS=%$
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/Tutorial/project.properties b/Tutorial/project.properties
deleted file mode 100644
index a3ee5ab..0000000
--- a/Tutorial/project.properties
+++ /dev/null
@@ -1,14 +0,0 @@
-# This file is automatically generated by Android Tools.
-# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
-#
-# This file must be checked in Version Control Systems.
-#
-# To customize properties used by the Ant build system edit
-# "ant.properties", and override values to adapt the script to your
-# project structure.
-#
-# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
-#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
-
-# Project target.
-target=android-17
diff --git a/Tutorial/res/drawable-hdpi/ic_gesturebuilder.png b/Tutorial/res/drawable-hdpi/ic_gesturebuilder.png
deleted file mode 100755
index 595b9e1..0000000
Binary files a/Tutorial/res/drawable-hdpi/ic_gesturebuilder.png and /dev/null differ
diff --git a/Tutorial/res/drawable-mdpi/ic_gesturebuilder.png b/Tutorial/res/drawable-mdpi/ic_gesturebuilder.png
deleted file mode 100644
index 1768375..0000000
Binary files a/Tutorial/res/drawable-mdpi/ic_gesturebuilder.png and /dev/null differ
diff --git a/Tutorial/settings.gradle b/Tutorial/settings.gradle
new file mode 100644
index 0000000..9ccfb61
--- /dev/null
+++ b/Tutorial/settings.gradle
@@ -0,0 +1 @@
+include ':app', ':wear'
diff --git a/Tutorial/src/com/androidmontreal/gesturevoicecommander/practice/MakeItListenAndRepeat.java b/Tutorial/src/com/androidmontreal/gesturevoicecommander/practice/MakeItListenAndRepeat.java
deleted file mode 100644
index 6e2b10a..0000000
--- a/Tutorial/src/com/androidmontreal/gesturevoicecommander/practice/MakeItListenAndRepeat.java
+++ /dev/null
@@ -1,133 +0,0 @@
-package com.androidmontreal.gesturevoicecommander.practice;
-
-import java.util.ArrayList;
-import java.util.Locale;
-
-import android.app.Activity;
-import android.content.Intent;
-import android.os.Bundle;
-import android.speech.RecognizerIntent;
-import android.speech.tts.TextToSpeech;
-import android.speech.tts.TextToSpeech.OnInitListener;
-import android.util.Log;
-import android.widget.Toast;
-
-import com.androidmontreal.gesturevoicecommander.R;
-
-/**
- *
- * Building on what we saw in MakeItTalk, now lets make it Listen. Here is some
- * super simple code that uses the VoiceRecognition Intent to recognize what the
- * user says, and then uses Text To Speech to tell the user what it might have
- * heard.
- *
- * @author cesine
- *
- */
-public class MakeItListenAndRepeat extends Activity implements OnInitListener {
- private static final String TAG = "MakeItListen";
- private static final int RETURN_FROM_VOICE_RECOGNITION_REQUEST_CODE = 341;
- /** Talk to the user */
- private TextToSpeech mTts;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- mTts = new TextToSpeech(this, this);
-
- }
-
- protected void promptTheUserToTalk() {
- mTts.speak(getString(R.string.im_listening), TextToSpeech.QUEUE_ADD, null);
- }
-
- /**
- * Fire an intent to start the voice recognition activity.
- */
- private void startVoiceRecognitionActivity() {
- Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
- intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
- RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
- intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
- getString(R.string.im_listening));
- startActivityForResult(intent, RETURN_FROM_VOICE_RECOGNITION_REQUEST_CODE);
- }
-
- /**
- * Handle the results from the voice recognition activity.
- */
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- if (requestCode == RETURN_FROM_VOICE_RECOGNITION_REQUEST_CODE
- && resultCode == RESULT_OK) {
- /*
- * Populate the wordsList with the String values the recognition engine
- * thought it heard, and then Toast them to the user and say them out
- * loud.
- */
- ArrayList matches = data
- .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
- for (int iMightHaveHeardThis = 0; iMightHaveHeardThis < matches.size(); iMightHaveHeardThis++) {
-
- /* Build a carrierPhrase if you want it to make some sense */
- String carrierPhrase = getString(R.string.i_might_have_heard);
- if (iMightHaveHeardThis > 0) {
- carrierPhrase = getString(R.string.or_maybe);
- }
- carrierPhrase += " " + matches.get(iMightHaveHeardThis) + ".";
-
- Toast.makeText(this, carrierPhrase, Toast.LENGTH_LONG).show();
- mTts.speak(carrierPhrase, TextToSpeech.QUEUE_ADD, null);
-
- /*
- * Don't go on forever, it there are too many potential matches don't
- * say them all
- */
- if (iMightHaveHeardThis == 2 && matches.size() > 2) {
- mTts.speak(getString(R.string.there_were_others),
- TextToSpeech.QUEUE_ADD, null);
- break;
- }
- }
- }
- super.onActivityResult(requestCode, resultCode, data);
- }
-
- @Override
- protected void onDestroy() {
- if (mTts != null) {
- mTts.stop();
- mTts.shutdown();
- }
- super.onDestroy();
- }
-
- @Override
- public void onInit(int status) {
- if (status == TextToSpeech.SUCCESS) {
- int result = mTts.setLanguage(Locale.getDefault());
- if (result == TextToSpeech.LANG_MISSING_DATA
- || result == TextToSpeech.LANG_NOT_SUPPORTED) {
- Log.e(TAG, "Language is not available.");
- Toast.makeText(
- this,
- "The " + Locale.getDefault().getDisplayLanguage()
- + " TextToSpeech isn't installed, you can go into the "
- + "\nAndroid's settings in the "
- + "\nVoice Input and Output menu to turn it on. ",
- Toast.LENGTH_LONG).show();
- } else {
- // everything is working.
- promptTheUserToTalk();
- startVoiceRecognitionActivity();
- }
- } else {
- Toast.makeText(
- this,
- "Sorry, I can't talk to you because "
- + "I could not initialize TextToSpeech.", Toast.LENGTH_LONG)
- .show();
- }
- }
-}
diff --git a/Tutorial/src/com/androidmontreal/gesturevoicecommander/practice/MakeItTalk.java b/Tutorial/src/com/androidmontreal/gesturevoicecommander/practice/MakeItTalk.java
deleted file mode 100644
index c1810be..0000000
--- a/Tutorial/src/com/androidmontreal/gesturevoicecommander/practice/MakeItTalk.java
+++ /dev/null
@@ -1,67 +0,0 @@
-package com.androidmontreal.gesturevoicecommander.practice;
-
-import java.util.Locale;
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.speech.tts.TextToSpeech;
-import android.speech.tts.TextToSpeech.OnInitListener;
-import android.util.Log;
-import android.widget.Toast;
-
-import com.androidmontreal.gesturevoicecommander.R;
-
-public class MakeItTalk extends Activity implements OnInitListener {
- private static final String TAG = "MakeItTalk";
- /** Talk to the user */
- private TextToSpeech mTts;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- mTts = new TextToSpeech(this, this);
-
- }
-
- protected void sayFirstWords() {
- mTts.speak(getString(R.string.my_first_words), TextToSpeech.QUEUE_ADD, null);
- }
-
- @Override
- protected void onDestroy() {
- if (mTts != null) {
- mTts.stop();
- mTts.shutdown();
- }
- super.onDestroy();
- }
-
- @Override
- public void onInit(int status) {
- if (status == TextToSpeech.SUCCESS) {
- int result = mTts.setLanguage(Locale.getDefault());
- if (result == TextToSpeech.LANG_MISSING_DATA
- || result == TextToSpeech.LANG_NOT_SUPPORTED) {
- Log.e(TAG, "Language is not available.");
- Toast.makeText(
- this,
- "The " + Locale.getDefault().getDisplayLanguage()
- + " TextToSpeech isn't installed, you can go into the "
- + "\nAndroid's settings in the "
- + "\nVoice Input and Output menu to turn it on. ",
- Toast.LENGTH_LONG).show();
- } else {
- // everything is working.
- sayFirstWords();
- }
- } else {
- Toast.makeText(
- this,
-
- "Sorry, I can't talk to you because "
- + "I could not initialize TextToSpeech.", Toast.LENGTH_LONG)
- .show();
- }
- }
-}
diff --git a/Tutorial/src/com/androidmontreal/gesturevoicecommander/practice/MakeItUnderstandGestures.java b/Tutorial/src/com/androidmontreal/gesturevoicecommander/practice/MakeItUnderstandGestures.java
deleted file mode 100644
index 4be13f7..0000000
--- a/Tutorial/src/com/androidmontreal/gesturevoicecommander/practice/MakeItUnderstandGestures.java
+++ /dev/null
@@ -1,179 +0,0 @@
-package com.androidmontreal.gesturevoicecommander.practice;
-
-import java.util.ArrayList;
-import java.util.Locale;
-
-import android.app.Activity;
-import android.content.Intent;
-import android.gesture.Gesture;
-import android.gesture.GestureLibraries;
-import android.gesture.GestureLibrary;
-import android.gesture.GestureOverlayView;
-import android.gesture.Prediction;
-import android.gesture.GestureOverlayView.OnGesturePerformedListener;
-import android.os.Bundle;
-import android.speech.RecognizerIntent;
-import android.speech.tts.TextToSpeech;
-import android.speech.tts.TextToSpeech.OnInitListener;
-import android.util.Log;
-import android.view.View;
-import android.widget.Toast;
-
-import com.androidmontreal.gesturevoicecommander.GestureBuilderActivity;
-import com.androidmontreal.gesturevoicecommander.R;
-import com.androidmontreal.gesturevoicecommander.robots.RoverLexicon;
-
-/**
- *
- * Building on what we saw in MakeItListenAndRepeat, now lets make it understand
- * gestures, or speech (sometimes its too noisy or too public to speak to your
- * Android). Here is some super simple code that builds on the GestureBuilder
- * sample code to recognize what the user wants the Android to do, and then use
- * Text To Speech to tell the user what it might have understood.
- *
- * @author cesine
- *
- */
-public class MakeItUnderstandGestures extends Activity implements
- OnInitListener, OnGesturePerformedListener {
- private static final String TAG = "MakeItUnderstandGestures";
- private static final int RETURN_FROM_VOICE_RECOGNITION_REQUEST_CODE = 341;
- private static final boolean D = true;
-
- /** Talk to the user */
- private TextToSpeech mTts;
-
- /*
- * A gesture library we created with the GestureBuilder, saved on the SDCard
- * and then imported into the res/raw folder of this project
- */
- private GestureLibrary gestureLib;
-
- /* A little lexicon we made for the DFR Rover at Cloud Robotics Hackathon */
- private RoverLexicon lexicon;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- mTts = new TextToSpeech(this, this);
-
- GestureOverlayView gestureOverlayView = new GestureOverlayView(this);
- View inflate = getLayoutInflater().inflate(R.layout.commander, null);
- gestureOverlayView.addView(inflate);
- gestureOverlayView.addOnGesturePerformedListener(this);
- // gestureLib = GestureLibraries.fromFile(fileOnYourSDCard);
- gestureLib = GestureLibraries.fromRawResource(this, R.raw.gestures);
- if (!gestureLib.load()) {
- finish();
- }
- setContentView(gestureOverlayView);
-
- lexicon = new RoverLexicon();
-
- }
-
- protected void promptTheUserToTalk() {
- mTts.speak(getString(R.string.im_listening), TextToSpeech.QUEUE_ADD, null);
- }
-
- /**
- * Fire an intent to start the voice recognition activity.
- */
- private void startVoiceRecognitionActivity() {
- Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
- intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
- RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
- intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
- getString(R.string.im_listening));
- startActivityForResult(intent, RETURN_FROM_VOICE_RECOGNITION_REQUEST_CODE);
- }
-
- /**
- * Handle the results from the voice recognition activity.
- */
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- if (requestCode == RETURN_FROM_VOICE_RECOGNITION_REQUEST_CODE
- && resultCode == RESULT_OK) {
- ArrayList matches = data
- .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
- /* try to find a robot command in the first match */
- sendRobotThisCommand(matches.get(0));
- }
- super.onActivityResult(requestCode, resultCode, data);
- }
-
- @Override
- protected void onDestroy() {
- if (mTts != null) {
- mTts.stop();
- mTts.shutdown();
- }
- super.onDestroy();
- }
-
- @Override
- public void onInit(int status) {
- if (status == TextToSpeech.SUCCESS) {
- int result = mTts.setLanguage(Locale.getDefault());
- if (result == TextToSpeech.LANG_MISSING_DATA
- || result == TextToSpeech.LANG_NOT_SUPPORTED) {
- Log.e(TAG, "Language is not available.");
- Toast.makeText(
- this,
- "The " + Locale.getDefault().getDisplayLanguage()
- + " TextToSpeech isn't installed, you can go into the "
- + "\nAndroid's settings in the "
- + "\nVoice Input and Output menu to turn it on. ",
- Toast.LENGTH_LONG).show();
- } else {
- // everything is working.
- }
- } else {
- Toast.makeText(
- this,
- "Sorry, I can't talk to you because "
- + "I could not initialize TextToSpeech.", Toast.LENGTH_LONG)
- .show();
- }
- }
-
- @Override
- public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
- ArrayList predictions = gestureLib.recognize(gesture);
- for (Prediction prediction : predictions) {
- if (prediction.score > 3.0) {
- Log.d(TAG, "Detected this gesture " + prediction.name
- + " with a score of " + prediction.score);
- }
- }
- if (predictions.size() > 0) {
- sendRobotThisCommand(predictions.get(0).name);
- }
- }
-
- public String sendRobotThisCommand(String command) {
- String guessedCommand = lexicon.guessWhatToDo(command);
- Toast.makeText(this, guessedCommand, Toast.LENGTH_SHORT).show();
-
- if (Locale.getDefault().getLanguage().contains("fr")) {
- mTts.speak(lexicon.FR_CARRIER_PHRASE + guessedCommand,
- TextToSpeech.QUEUE_ADD, null);
- } else {
- mTts.speak(lexicon.EN_CARRIER_PHRASE + guessedCommand,
- TextToSpeech.QUEUE_ADD, null);
- }
- return lexicon.executeGuess();
- }
-
- public void onCommandByVoiceClick(View v) {
- promptTheUserToTalk();
- startVoiceRecognitionActivity();
- }
-
- public void onViewGesturesClick(View v) {
- Intent i = new Intent(this, GestureBuilderActivity.class);
- startActivity(i);
- }
-}
diff --git a/Tutorial/src/com/androidmontreal/gesturevoicecommander/robots/RoverLexicon.java b/Tutorial/src/com/androidmontreal/gesturevoicecommander/robots/RoverLexicon.java
deleted file mode 100644
index db87b2b..0000000
--- a/Tutorial/src/com/androidmontreal/gesturevoicecommander/robots/RoverLexicon.java
+++ /dev/null
@@ -1,192 +0,0 @@
-package com.androidmontreal.gesturevoicecommander.robots;
-
-import java.util.ArrayList;
-import java.util.Locale;
-
-public class RoverLexicon {
- private int language;
- private int timer = 5;
-
- /*
- * Languages
- */
- public static final int EN = 1000;
- public static final int FR = 1001;
- public static final String EN_CARRIER_PHRASE = "I will tell the robot: ";
- public static final String FR_CARRIER_PHRASE = "Je vais dire au robo: ";
-
- /*
- * Commands, use the order of these constants for the precedence order of the
- * commands (STOP has the highest precedence)
- */
- public static final int STOP = 0;
- public static final int EXPLORE = 1;
- public static final int FORWARD = 2;
- public static final int REVERSE = 3;
- public static final int TURNRIGHT = 6;
- public static final int TURNLEFT = 7;
- public static final int ROTATERIGHT = 4;
- public static final int ROTATELEFT = 5;
-
- private ArrayList en;
- private ArrayList fr;
-
- private int mCommandToExecute;
-
- public String stop() {
- return "S";
- }
-
- public String explore() {
- return "E";
- }
-
- public String forward() {
- return "1F2F";
- }
-
- public String reverse() {
- return "1R2R";
- }
-
- public String turnRight() {
- return "1F";
- }
-
- public String turnLeft() {
- return "2F";
- }
-
- public String rotateRight() {
- return "1F2R";
- }
-
- public String rotateLeft() {
- return "1R2F";
- }
-
- public void defineLanguages() {
- en = new ArrayList();
- en.add(EXPLORE, "explore:try");
- en.add(FORWARD, "forward:ahead");
- en.add(REVERSE, "reverse:back");
- en.add(ROTATERIGHT, "rotate&right");
- en.add(ROTATELEFT, "rotate&left");
- en.add(TURNRIGHT, "right");
- en.add(TURNLEFT, "left");
- en.add(STOP, "stop:wait:don't:no:damn");
-
- fr = new ArrayList();
- fr.add(EXPLORE, "explore");
- fr.add(FORWARD, "avance:forward");
- fr.add(REVERSE, "recule:reverse");
- fr.add(ROTATERIGHT, "rotate&droit");
- fr.add(ROTATELEFT, "rotate&gauche");
- fr.add(TURNRIGHT, "droit:right");
- fr.add(TURNLEFT, "gauche:left");
- fr.add(STOP, "arrter:pas:voyons:merde:zut:non:stop");
-
- }
-
- public String execute(int commandInteger) {
- switch (commandInteger) {
- case STOP:
- return stop();
- case EXPLORE:
- return explore();
- case FORWARD:
- return forward();
- case REVERSE:
- return reverse();
- case TURNRIGHT:
- return turnRight();
- case TURNLEFT:
- return turnLeft();
- case ROTATERIGHT:
- return rotateRight();
- case ROTATELEFT:
- return rotateLeft();
- default:
- return stop();
- }
- }
-
- public String guessWhatToDo(String command) {
- command = command.toLowerCase();
- int commandToExecute = STOP;
- String commandForHumans = command;
-
- ArrayList humancommands = en;
- if (language == FR) {
- humancommands = fr;
- }
- for (int i = 0; i < humancommands.size(); i++) {
- String[] andwords = humancommands.get(i).split("&");
- String[] orwords = humancommands.get(i).split(":");
- /*
- * If there are AND words, then check first to see if it matches all words
- */
- if (andwords.length > 1) {
- int wordsfound = 0;
- commandForHumans = andwords[0];
- for (int k = 0; k < andwords.length; k++) {
- if (command.contains(andwords[k])) {
- wordsfound++;
- }
- }
- if (wordsfound >= andwords.length) {
- commandToExecute = i;
- return commandForHumans;
- }
- }
- /*
- * Then if a command hasn't been issued, check for the OR words.
- */
- if (orwords.length > 0) {
- commandForHumans = orwords[0];
- for (int k = 0; k < orwords.length; k++) {
- if (command.contains(orwords[k])) {
- commandToExecute = i;
- return commandForHumans;
- }
- }
- }
-
- }
- mCommandToExecute = commandToExecute;
- return commandForHumans;
- }
-
- public String executeGuess() {
- if (mCommandToExecute >= 0) {
- return execute(mCommandToExecute);
- }
- return "";
- }
-
- public RoverLexicon(int language, int timer) {
- super();
- defineLanguages();
- this.language = language;
- this.timer = timer;
- }
-
- public RoverLexicon(int language) {
- super();
- defineLanguages();
- this.language = language;
- this.timer = 5;
- }
-
- public RoverLexicon() {
- super();
- defineLanguages();
- if (Locale.getDefault().getLanguage().contains("fr")) {
- this.language = FR;
- } else {
- this.language = EN;
- }
- this.timer = 5;
- }
-
-}
diff --git a/Tutorial/wear/build.gradle b/Tutorial/wear/build.gradle
new file mode 100644
index 0000000..617d4d6
--- /dev/null
+++ b/Tutorial/wear/build.gradle
@@ -0,0 +1,28 @@
+apply plugin: 'com.android.application'
+
+
+android {
+ compileSdkVersion 23
+ buildToolsVersion "23.0.2"
+
+ defaultConfig {
+ applicationId "com.androidmontreal.gesturevoicecontroller"
+ minSdkVersion 21
+ targetSdkVersion 23
+ versionCode 1
+ versionName "1.0"
+ }
+ buildTypes {
+ release {
+ minifyEnabled false
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+ }
+ }
+}
+
+dependencies {
+ compile fileTree(dir: 'libs', include: ['*.jar'])
+ compile 'watch.nudge.gesturelibrary:gesturelibrary:0.8.10'
+ compile 'com.google.android.support:wearable:1.3.0'
+ compile 'com.google.android.gms:play-services-wearable:7.8.0'
+}
diff --git a/Tutorial/wear/src/main/AndroidManifest.xml b/Tutorial/wear/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..83cc660
--- /dev/null
+++ b/Tutorial/wear/src/main/AndroidManifest.xml
@@ -0,0 +1,52 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Tutorial/wear/src/main/java/com/androidmontreal/gesturevoicecontroller/GestureLaunchReceiver.java b/Tutorial/wear/src/main/java/com/androidmontreal/gesturevoicecontroller/GestureLaunchReceiver.java
new file mode 100644
index 0000000..3a7a0d0
--- /dev/null
+++ b/Tutorial/wear/src/main/java/com/androidmontreal/gesturevoicecontroller/GestureLaunchReceiver.java
@@ -0,0 +1,13 @@
+package com.androidmontreal.gesturevoicecontroller;
+
+import watch.nudge.gesturelibrary.AppControllerReceiverService;
+
+/**
+ * Created by on 15-12-12.
+ */
+public class GestureLaunchReceiver extends AppControllerReceiverService {
+ @Override
+ protected Class getWatchActivityClass() {
+ return MainWatchActivity.class;
+ }
+}
diff --git a/Tutorial/wear/src/main/java/com/androidmontreal/gesturevoicecontroller/MainWatchActivity.java b/Tutorial/wear/src/main/java/com/androidmontreal/gesturevoicecontroller/MainWatchActivity.java
new file mode 100644
index 0000000..73a8341
--- /dev/null
+++ b/Tutorial/wear/src/main/java/com/androidmontreal/gesturevoicecontroller/MainWatchActivity.java
@@ -0,0 +1,118 @@
+package com.androidmontreal.gesturevoicecontroller;
+
+import android.os.Bundle;
+import android.support.wearable.activity.WearableActivity;
+import android.support.wearable.view.BoxInsetLayout;
+import android.view.View;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Locale;
+
+import watch.nudge.gesturelibrary.AbstractGestureClientActivity;
+import watch.nudge.gesturelibrary.DefaultUnwindowedGestureActivity;
+import watch.nudge.gesturelibrary.GestureConstants;
+
+public class MainWatchActivity extends AbstractGestureClientActivity {
+
+ private static final SimpleDateFormat AMBIENT_DATE_FORMAT =
+ new SimpleDateFormat("HH:mm", Locale.US);
+
+ private BoxInsetLayout mContainerView;
+ private TextView mTextView;
+ private TextView mClockView;
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_main_watch);
+ setAmbientEnabled();
+
+ mContainerView = (BoxInsetLayout) findViewById(R.id.container);
+ mTextView = (TextView) findViewById(R.id.text);
+ mClockView = (TextView) findViewById(R.id.clock);
+
+ setSubscribeWindowEvents(true);
+ }
+
+ @Override
+ public ArrayList getGestureSubscpitionList() {
+ ArrayList gestures = new ArrayList();
+ gestures.add(GestureConstants.SubscriptionGesture.FLICK);
+ gestures.add(GestureConstants.SubscriptionGesture.SNAP);
+ gestures.add(GestureConstants.SubscriptionGesture.TWIST);
+ gestures.add(GestureConstants.SubscriptionGesture.TILT_X);
+ gestures.add(GestureConstants.SubscriptionGesture.TILT);
+ return gestures;
+ }
+
+ @Override
+ public void onSnap() {
+ Toast.makeText(this,"Stop", Toast.LENGTH_LONG).show();
+ }
+
+ @Override
+ public void onFlick() {
+ Toast.makeText(this,"Explore",Toast.LENGTH_LONG).show();
+ }
+
+ @Override
+ public void onTwist() {
+ Toast.makeText(this,"Rotate",Toast.LENGTH_LONG).show();
+ }
+
+ @Override
+ public void onGestureWindowClosed() {
+ Toast.makeText(this,"Gesture window closed.",Toast.LENGTH_LONG).show();
+ }
+
+ @Override
+ public void onTiltX(float x) {
+ Toast.makeText(this,"onTiltX " + x,Toast.LENGTH_LONG).show();
+ }
+
+ @Override
+ public void onTilt(float x, float y, float z) {
+ Toast.makeText(this,"onTilt " + x + " " + y + " " + z,Toast.LENGTH_LONG).show();
+ }
+
+ @Override
+ public boolean sendsGestureToPhone() {
+ return true;
+ }
+
+ @Override
+ public void onEnterAmbient(Bundle ambientDetails) {
+ super.onEnterAmbient(ambientDetails);
+ updateDisplay();
+ }
+
+ @Override
+ public void onUpdateAmbient() {
+ super.onUpdateAmbient();
+ updateDisplay();
+ }
+
+ @Override
+ public void onExitAmbient() {
+ updateDisplay();
+ super.onExitAmbient();
+ }
+
+ private void updateDisplay() {
+ if (isAmbient()) {
+ mContainerView.setBackgroundColor(getResources().getColor(android.R.color.black));
+ mTextView.setTextColor(getResources().getColor(android.R.color.white));
+ mClockView.setVisibility(View.VISIBLE);
+
+ mClockView.setText(AMBIENT_DATE_FORMAT.format(new Date()));
+ } else {
+ mContainerView.setBackground(null);
+ mTextView.setTextColor(getResources().getColor(android.R.color.black));
+ mClockView.setVisibility(View.GONE);
+ }
+ }
+}
diff --git a/Tutorial/wear/src/main/res/layout/activity_main_watch.xml b/Tutorial/wear/src/main/res/layout/activity_main_watch.xml
new file mode 100644
index 0000000..d01bd3a
--- /dev/null
+++ b/Tutorial/wear/src/main/res/layout/activity_main_watch.xml
@@ -0,0 +1,25 @@
+
+
+
+
+
+
+
+
diff --git a/Tutorial/wear/src/main/res/mipmap-hdpi/ic_launcher.png b/Tutorial/wear/src/main/res/mipmap-hdpi/ic_launcher.png
new file mode 100644
index 0000000..d62b72a
Binary files /dev/null and b/Tutorial/wear/src/main/res/mipmap-hdpi/ic_launcher.png differ
diff --git a/Tutorial/wear/src/main/res/mipmap-mdpi/ic_launcher.png b/Tutorial/wear/src/main/res/mipmap-mdpi/ic_launcher.png
new file mode 100644
index 0000000..6064d9e
Binary files /dev/null and b/Tutorial/wear/src/main/res/mipmap-mdpi/ic_launcher.png differ
diff --git a/Tutorial/wear/src/main/res/values/strings.xml b/Tutorial/wear/src/main/res/values/strings.xml
new file mode 100644
index 0000000..64a270b
--- /dev/null
+++ b/Tutorial/wear/src/main/res/values/strings.xml
@@ -0,0 +1,3 @@
+
+ Controller
+
diff --git a/python-serial/pyserial/CHANGES.txt b/python-serial/pyserial/CHANGES.txt
deleted file mode 100644
index 4271289..0000000
--- a/python-serial/pyserial/CHANGES.txt
+++ /dev/null
@@ -1,434 +0,0 @@
-========================
- pySerial Release Notes
-========================
-
-Version 1.0 13 Feb 2002
----------------------------
-- First public release.
-- Split from the pybsl application (see http://mspgcc.sourceforge.net)
-
-New Features:
-
-- Added Jython support
-
-
-Version 1.1 14 Feb 2002
----------------------------
-Bugfixes:
-
-- Win32, when not specifying a timeout
-- Typos in the Docs
-
-New Features:
-
-- added ``serialutil`` which provides a base class for the ``Serial``
- objects.
-
-- ``readline``, ``readlines``, ``writelines`` and ``flush`` are now supported
- see README.txt for deatils.
-
-
-Version 1.11 14 Feb 2002
----------------------------
-Same as 1.1 but added missing files.
-
-
-Version 1.12 18 Feb 2002
----------------------------
-Removed unneded constants to fix RH7.x problems.
-
-
-Version 1.13 09 Apr 2002
----------------------------
-Added alternate way for enabling rtscts (CNEW_RTSCTS is tried too)
-If port opening fails, a ``SerialException`` is raised on all platforms
-
-
-Version 1.14 29 May 2002
----------------------------
-Added examples to archive
-Added non-blocking mode for ``timeout=0`` (tnx Mat Martineau)
-
-Bugfixes:
-
-- win32 does now return the remaining characters on timeout
-
-
-Version 1.15 04 Jun 2002
----------------------------
-Bugfixes (win32):
-
-- removed debug messages
-- compatibility to win9x improved
-
-
-Version 1.16 02 Jul 2002
----------------------------
-Added implementation of RI and corrected RTS/CTS on Win32
-
-
-Version 1.17 03 Jul 2002
----------------------------
-Silly mix of two versions in win32 code corrected
-
-
-Version 1.18 06 Dec 2002
----------------------------
-Bugfixes (general):
-
-- remove the mapping of flush to the destructive flushOutput as
- this is not the expected behaviour.
-- readline: EOL character for lines can be chosen idea by
- John Florian.
-
-Bugfixes (posix):
-
-- cygwin port numbering fixed
-- test each and every constant for it's existence in termios module,
- use default if not existent (fix for Bug item #640214)
-- wrong exception on nonexistent ports with /dev file. bug report
- by Louis Cordier
-
-Bugfixes (win32):
-
-- RTS/CTS handling as suggested in Bug #635072
-- bugfix of timeouts brought up by Markus Hoffrogge
-
-
-Version 1.19 19 Mar 2003
----------------------------
-Bugfixes (posix):
-
-- removed ``dgux`` entry which actually had a wrong comment and is
- probably not in use anywhere.
-
-Bugfixes (win32):
-
-- added ``int()`` conversion, [Bug 702120]
-- remove code to set control lines in close method of win32
- version. [Bug 669625]
-
-
-Version 1.20 28 Aug 2003
----------------------------
-- Added ``serial.device()`` for all platforms
-
-Bugfixes (win32):
-
-- don't recreate overlapped structures and events on each
- read/write.
-- don't set unneeded event masks.
-- dont use DOS device names for ports > 9.
-- remove send timeout (its not used in the linux impl. anyway).
-
-
-Version 1.21 30 Sep 2003
----------------------------
-Bugfixes (win32):
-
-- name for COM10 was not built correctly, found by Norm Davis.
-
-Bugfixes (examples):
-
-- small change in ``miniterm.py`` that should mage it run on cygwin,
- [Bug 809904] submitted by Rolf Campbell.
-
-
-Version 2.0b1 1 Oct 2003
----------------------------
-Transition to the Python 2.0 series:
-
-- New implementation only supports Python 2.2+, backwards compatibility
- should be maintained almost everywhere.
- The OS handles (like the ``hComPort`` or ``fd`` attribute) were prefixed
- with an underscore. The different names stay, as anyone that uses one of
- these has to write platform specific code anyway.
-- Common base class ``serialutil.SerialBase`` for all implementations.
-- ``PARITY_NONE``, ``PARITY_EVEN``, ``PARITY_ODD`` constants changed and all
- these constants moved to ``serialutil.py`` (still available as
- ``serial.PARITY_NONE`` etc. and they should be used that way)
-- Added ``serial.PARITY_NAMES`` (implemented in ``serialutil.PARITY_NAMES``).
- This dictionary can be used to convert parity constants to meaningful
- strings.
-- Each Serial class and instance has a list of supported values:
- ``BAUDRATES``, ``BYTESIZES``, ``PARITIES``, ``STOPBITS``Ggg
- (i.e. ``serial.Serial.BAUDRATES or s = serial.Serial; s.BAUDRATES``)
- these values can be used to fill in value sin GUI dialogs etc.
-- Creating a ``Serial()`` object without port spec returns an unconfigured,
- closed port. Useful if a GUI dialog should take a port and configure
- it.
-- New methods for ``serial.Serial`` instances: ``open()``, ``isOpen()``
-- A port can be opened and closed as many times as desired.
-- Instances of ``serial.Serial`` have ``baudrate``, ``bytesize``, ``timeout``
- etc. attributes implemented as properties, all can be set while the port is
- opened. It will then be reconfigured.
-- Improved ``__doc__``'s.
-- New ``test_advanced.py`` for the property setting/getting testing.
-- Small bugfix on posix with get* methods (return value should be true a
- boolean).
-- added a ``__repr__`` that returns a meaningful string will all the serial
- setting, easy for debugging.
-- The serialposix module does not throw an exception on unsupported
- platforms, the message is still printed. The idea that it may still
- work even if the platform itself s not known, it simply tries to do
- the posix stuff anyway (It's likely that opening ports by number
- fails, but by name it should work).
-
-
-Version 2.0b2 4 Oct 2003
----------------------------
-- Added serial port configuration dialog for wxPython to the examples.
-- Added terminal application for wxPython with wxGlade design file
- to the examples.
-- Jython support is currently broken as Jython does not have a Python 2.2
- compatible release out yet
-
-
-Version 2.0 6 Nov 2003
----------------------------
-- Fixes ``setup.py`` for older distutils
-
-
-Version 2.1 28 Jul 2004
----------------------------
-Bugfixes:
-
-- Fix XON/XOFF values [Bug 975250]
-
-Bugfixes (posix):
-
-- ``fd == 0`` fix from Vsevolod Lobko
-- netbsd fixes from Erik Lindgren
-- Dynamicaly lookup baudrates and some cleanups
-
-Bugfixes (examples):
-
-- CRLF handling of ``miniterm.py`` should be more consistent on Win32
- and others. Added LF only command line option
-- Multithreading fixes to ``wxTerminal.py`` (helps with wxGTK)
-- Small change for wxPython 2.5 in ``wxSerialConfigDialog.py`` [Bug 994856]
-
-New Features:
-
-- Implement write timeouts (``writeTimeout`` parameter)
-
-
-Version 2.2 31 Jul 2005
----------------------------
-Bugfixes:
-
-- [Bug 1014227]: property broken
-- [Bug 1105687]: ``serial_tcp_example.py``: ``--localport`` option
-- [Bug 1106313]: device (port) strings cannot be unicode
-
-Bugfixes (posix):
-
-- [Patch 1043436] Fix for [Bug 1043420] (OSError: EAGAIN)
-- [Patch 1102700] ``fileno()`` added
-- ensure disabled PARMRK
-
-Bugfixes (win32):
-
-- [Patch 983106]: keep RTS/CTS state on port setting changes
-
-New Features:
-
-- ``dsrdtr`` setting to enable/disable DSR/DTR flow control independently
- from the ``rtscts`` setting. (Currenly Win32 only, ignored on other
- platforms)
-
-
-Version 2.3 19 Jun 2008
----------------------------
-New Features:
-
-- iterator interface. ``for line in Serial(...): ...`` is now possible
- Suggested by Bernhard Bender
-- ``sendBreak()`` accepts a ``duration`` argument. Default duration increased.
-- win32 handles \\.\COMx format automatically for com ports of higher number
- (COM10 is internally translated to \\.\COM10 etc.)
-- miniterm.py has a new feature to send a file (upload) and configurable
- special characters for exit and upload. Refactored internals to class based
- structure (upload and class refactoring by Colin D Bennett)
-
-Bugfixes:
-
-- [Bug 1451535] TCP/serial redirect example "--help"
-- update VERSION variable
-- update wxSerialConfigDialog.py and wxTerminal.py compatibility with
- wxPython 2.8 (Peleg)
-- Check for string in write function. Using unicode causes errors, this
- helps catching errors early (Tom Lynn)
-
-Bugfixes (posix):
-
-- [Bug 1554183] setRTS/setDTR reference to non existing local "on"
-- [Bug 1513653] file descriptor not closed when exception is thrown
-- FreeBSD now uses cuadX instead of cuaaX (Patrick Phalen)
-
-Bugfixes (win32):
-
-- [Bug 1520357] Handle leak
-- [Bug 1679013] Ignore exception raised by SetCommTimeout() in close().
-- [Bug 1938118] process hang forever under XP
-
-
-Version 2.4 6 Jul 2008
----------------------------
-New Features:
-
-- [Patch 1616790] pyserial: Add inter-character timeout feature
-- [Patch 1924805] add a setBreak function
-- Add mark/space parity
-- Add .NET/Mono backend (IronPython)
-
-Bugfixes (posix):
-
-- [Bug 1783159] Arbitrary baud rates (Linux/Posix)
-
-Bugfixes (win32):
-
-- [Patch 1561423] Add mark/space parity, Win32
-- [Bug 2000771] serial port CANNOT be specified by number on windows
-- examples/scanwin32.py does no longer return \\.\ names
-- fix \\.\ handling for some cases
-
-Bugfixes (jython):
-
- - The Jython backend tries javax.comm and gnu.io (Seo Sanghyeon)
-
-
-Version 2.5-rc1 2009-07-30
----------------------------
-New Features:
-
-- Python 3.x support (through 2to3)
-- compatible with Python io library (Python 2.6+)
-- Support for Win32 is now written on the top of ctypes (bundled with
- Python 2.5+) instead of pywin32 (patch by Giovanni Bajo).
-- 1.5 stop bits (STOPBITS_ONE_POINT_FIVE, implemented on all platforms)
-- miniterm application extended (CTRL+T -> menu)
-- miniterm.py is now installed as "script"
-- add scanlinux.py example
-- add port_publisher example
-- experimental RFC-2217 server support (examples/rfc2217_server.py)
-- add ``getSettingsDict`` and ``applySettingsDict`` serial object methods
-- use a ``poll`` based implementation on Posix, instead of a ``select`` based,
- provides better error handling [removed again in later releases].
-
-Bugfixes:
-
-- Improve and fix tcp_serial_redirector example.
-- [Bug 2603052] 5-bit mode (needs 1.5 stop bits in some cases)
-
-Bugfixes (posix):
-
-- [Bug 2810169] Propagate exceptions raised in serialposix _reconfigure
-- [Bug 2562610] setting non standard baud rates on Darwin (Emmanuel Blot)
-
-Bugfixes (win32):
-
-- [Bug 2469098] parity PARITY_MARK, PARITY_SPACE isn't supported on win32
-- [SF 2446218] outWaiting implemented
-- [Bug 2392892] scanwin32.py better exception handling
-- [Bug 2505422] scanwin32.py Vista 64bit compatibility
-
-
-Version 2.5-rc2 2010-01-02
----------------------------
-New Features:
-
-- Documentation update, now written with Sphinx/ReST
-- Updated miniterm.py example
-- experimental RFC-2217 client support (serial.rfc2217.Serial, see docs)
-- add ``loop://`` device for testing.
-- add ``serial.serial_for_url`` factory function (support for native ports and
- ``rfc2217``, ``socket`` and ``loop`` URLs)
-- add new example: ``rfc2217_server.py``
-- tests live in their own directory now (no longer in examples)
-
-Bugfixes:
-
-- [Bug 2915810] Fix for suboption parsing in rfc2217
-- Packaging bug (missed some files)
-
-Bugfixes (posix):
-
-- improve write timeout behavior
-- [Bug 2836297] move Linux specific constants to not break other platforms
-- ``poll`` based implementation for ``read`` is in a separate class
- ``PosixPollSerial``, as it is not supported well on all platforms (the
- default ``Serial`` class uses select).
-- changed error handling in ``read`` so that disconnected devices are
- detected.
-
-
-Bugfixes (win32):
-
-- [Bug 2886763] hComPort doesn't get initialized for Serial(port=None)
-
-
-Version 2.5 2010-07-22
----------------------------
-New Features:
-
-- [Bug 2976262] dsrdtr should default to False
- ``dsrdtr`` parameter default value changed from ``None`` (follow ``rtscts``
- setting) to ``False``. This means ``rtscts=True`` enables hardware flow
- control on RTS/CTS but no longer also on DTR/DSR. This change mostly
- affects Win32 as on other platforms, that setting was ignored anyway.
-- Improved xreadlines, it is now a generator function that yields lines as they
- are received (previously it called readlines which would only return all
- lines read after a read-timeout). However xreadlines is deprecated an not
- available when the io module is used. Use ``for line in Serial(...):``
- instead.
-
-Bugfixes:
-
-- [Bug 2925854] test.py produces exception with python 3.1
-- [Bug 3029812] 2.5rc2 readline(s) doesn't work
-
-Bugfixes (posix):
-
-- [BUG 3006606] Nonblocking error - Unix platform
-
-Bugfixes (win32):
-
-- [Bug 2998169] Memory corruption at faster transmission speeds.
- (bug introduced in 2.5-rc1)
-
-
-Version 2.6 2011-11-02
----------------------------
-New Features:
-
-- Moved some of the examples to serial.tools so that they can be used
- with ``python -m``
-- serial port enumeration now included as ``serial.tools.list_ports``
-- URL handers for ``serial_for_url`` are now imported dynamically. This allows
- to add protocols w/o editing files. The list
- ``serial.protocol_handler_packages`` can be used to add or remove user
- packages with protocol handlers (see docs for details).
-- new URL type: hwgrep:// uses list_ports module to search for ports
- by their description
-- serveral internal changes to improve Python 3.x compatibility (setup.py,
- use of absolute imports and more)
-
-Bugfixes:
-
-- [Bug 3093882] calling open() on an already open port now raises an exception
-- [Bug 3245627] connection-lost let rfc2217 hangs in closed loop
-- [Patch 3147043] readlines() to support multi-character eol
-
-Bugfixes (posix):
-
-- [Patch 3316943] Avoid unneeded termios.tcsetattr calls in serialposix.py
-- [Patch 2912349] Serial Scan as a Module with Mac Support
-
-Bugfixes (win32):
-
-- [Bug 3057499] writeTimeoutError when write Timeout is 0
-- [Bug 3414327] Character out of range in list_ports_windows
-- [Patch 3036175] Windows 98 Support fix
-- [Patch 3054352] RTS automatic toggle, for RS485 functionality.
-- Fix type definitions for 64 bit Windows compatibility
diff --git a/python-serial/pyserial/LICENSE.txt b/python-serial/pyserial/LICENSE.txt
deleted file mode 100644
index 7bfac33..0000000
--- a/python-serial/pyserial/LICENSE.txt
+++ /dev/null
@@ -1,61 +0,0 @@
-Copyright (c) 2001-2011 Chris Liechti ;
-All Rights Reserved.
-
-This is the Python license. In short, you can use this product in
-commercial and non-commercial applications, modify it, redistribute it.
-A notification to the author when you use and/or modify it is welcome.
-
-
-TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING THIS SOFTWARE
-===================================================================
-
-LICENSE AGREEMENT
------------------
-
-1. This LICENSE AGREEMENT is between the copyright holder of this
-product, and the Individual or Organization ("Licensee") accessing
-and otherwise using this product in source or binary form and its
-associated documentation.
-
-2. Subject to the terms and conditions of this License Agreement,
-the copyright holder hereby grants Licensee a nonexclusive,
-royalty-free, world-wide license to reproduce, analyze, test,
-perform and/or display publicly, prepare derivative works, distribute,
-and otherwise use this product alone or in any derivative version,
-provided, however, that copyright holders License Agreement and
-copyright holders notice of copyright are retained in this product
-alone or in any derivative version prepared by Licensee.
-
-3. In the event Licensee prepares a derivative work that is based on
-or incorporates this product or any part thereof, and wants to make
-the derivative work available to others as provided herein, then
-Licensee hereby agrees to include in any such work a brief summary of
-the changes made to this product.
-
-4. The copyright holder is making this product available to Licensee on
-an "AS IS" basis. THE COPYRIGHT HOLDER MAKES NO REPRESENTATIONS OR
-WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION,
-THE COPYRIGHT HOLDER MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
-WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR
-THAT THE USE OF THIS PRODUCT WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
-
-5. THE COPYRIGHT HOLDER SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER
-USERS OF THIS PRODUCT FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL
-DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE
-USING THIS PRODUCT, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE
-POSSIBILITY THEREOF.
-
-6. This License Agreement will automatically terminate upon a material
-breach of its terms and conditions.
-
-7. Nothing in this License Agreement shall be deemed to create any
-relationship of agency, partnership, or joint venture between the
-copyright holder and Licensee. This License Agreement does not grant
-permission to use trademarks or trade names from the copyright holder
-in a trademark sense to endorse or promote products or services of
-Licensee, or any third party.
-
-8. By copying, installing or otherwise using this product, Licensee
-agrees to be bound by the terms and conditions of this License
-Agreement.
-
diff --git a/python-serial/pyserial/MANIFEST.in b/python-serial/pyserial/MANIFEST.in
deleted file mode 100644
index b16631a..0000000
--- a/python-serial/pyserial/MANIFEST.in
+++ /dev/null
@@ -1,35 +0,0 @@
-include README.txt
-include LICENSE.txt
-include CHANGES.txt
-include MANIFEST.in
-include setup.py
-
-include examples/enhancedserial.py
-include examples/miniterm.py
-include examples/port_publisher.py
-include examples/port_publisher.sh
-include examples/rfc2217_server.py
-include examples/scan.py
-include examples/scanlinux.py
-include examples/scanwin32.py
-include examples/setup-miniterm-py2exe.py
-include examples/setup-rfc2217_server-py2exe.py
-include examples/setup-wxTerminal-py2exe.py
-include examples/tcp_serial_redirect.py
-include examples/wxSerialConfigDialog.py
-include examples/wxSerialConfigDialog.wxg
-include examples/wxTerminal.py
-include examples/wxTerminal.wxg
-
-include test/run_all_tests.py
-include test/test.py
-include test/test_advanced.py
-include test/test_high_load.py
-include test/test_io_lib.py
-include test/test_readline.py
-
-include documentation/*.rst
-include documentation/pyserial.png
-include documentation/conf.py
-include documentation/Makefile
-
diff --git a/python-serial/pyserial/build/lib/serial/__init__.py b/python-serial/pyserial/build/lib/serial/__init__.py
deleted file mode 100644
index 759fc94..0000000
--- a/python-serial/pyserial/build/lib/serial/__init__.py
+++ /dev/null
@@ -1,79 +0,0 @@
-#!/usr/bin/env python
-
-# portable serial port access with python
-# this is a wrapper module for different platform implementations
-#
-# (C) 2001-2010 Chris Liechti
-# this is distributed under a free software license, see license.txt
-
-VERSION = '2.6'
-
-import sys
-
-if sys.platform == 'cli':
- from serial.serialcli import *
-else:
- import os
- # chose an implementation, depending on os
- if os.name == 'nt': #sys.platform == 'win32':
- from serial.serialwin32 import *
- elif os.name == 'posix':
- from serial.serialposix import *
- elif os.name == 'java':
- from serial.serialjava import *
- else:
- raise ImportError("Sorry: no implementation for your platform ('%s') available" % (os.name,))
-
-
-protocol_handler_packages = [
- 'serial.urlhandler',
- ]
-
-def serial_for_url(url, *args, **kwargs):
- """\
- Get an instance of the Serial class, depending on port/url. The port is not
- opened when the keyword parameter 'do_not_open' is true, by default it
- is. All other parameters are directly passed to the __init__ method when
- the port is instantiated.
-
- The list of package names that is searched for protocol handlers is kept in
- ``protocol_handler_packages``.
-
- e.g. we want to support a URL ``foobar://``. A module
- ``my_handlers.protocol_foobar`` is provided by the user. Then
- ``protocol_handler_packages.append("my_handlers")`` would extend the search
- path so that ``serial_for_url("foobar://"))`` would work.
- """
- # check remove extra parameter to not confuse the Serial class
- do_open = 'do_not_open' not in kwargs or not kwargs['do_not_open']
- if 'do_not_open' in kwargs: del kwargs['do_not_open']
- # the default is to use the native version
- klass = Serial # 'native' implementation
- # check port type and get class
- try:
- url_nocase = url.lower()
- except AttributeError:
- # it's not a string, use default
- pass
- else:
- if '://' in url_nocase:
- protocol = url_nocase.split('://', 1)[0]
- for package_name in protocol_handler_packages:
- module_name = '%s.protocol_%s' % (package_name, protocol,)
- try:
- handler_module = __import__(module_name)
- except ImportError:
- pass
- else:
- klass = sys.modules[module_name].Serial
- break
- else:
- raise ValueError('invalid URL, protocol %r not known' % (protocol,))
- else:
- klass = Serial # 'native' implementation
- # instantiate and open when desired
- instance = klass(None, *args, **kwargs)
- instance.port = url
- if do_open:
- instance.open()
- return instance
diff --git a/python-serial/pyserial/build/lib/serial/rfc2217.py b/python-serial/pyserial/build/lib/serial/rfc2217.py
deleted file mode 100644
index 776a210..0000000
--- a/python-serial/pyserial/build/lib/serial/rfc2217.py
+++ /dev/null
@@ -1,1284 +0,0 @@
-#! python
-#
-# Python Serial Port Extension for Win32, Linux, BSD, Jython
-# see __init__.py
-#
-# This module implements a RFC2217 compatible client. RF2217 descibes a
-# protocol to access serial ports over TCP/IP and allows setting the baud rate,
-# modem control lines etc.
-#
-# (C) 2001-2009 Chris Liechti
-# this is distributed under a free software license, see license.txt
-
-# TODO:
-# - setting control line -> answer is not checked (had problems with one of the
-# severs). consider implementing a compatibility mode flag to make check
-# conditional
-# - write timeout not implemented at all
-
-##############################################################################
-# observations and issues with servers
-#=============================================================================
-# sredird V2.2.1
-# - http://www.ibiblio.org/pub/Linux/system/serial/ sredird-2.2.2.tar.gz
-# - does not acknowledge SET_CONTROL (RTS/DTR) correctly, always responding
-# [105 1] instead of the actual value.
-# - SET_BAUDRATE answer contains 4 extra null bytes -> probably for larger
-# numbers than 2**32?
-# - To get the signature [COM_PORT_OPTION 0] has to be sent.
-# - run a server: while true; do nc -l -p 7000 -c "sredird debug /dev/ttyUSB0 /var/lock/sredir"; done
-#=============================================================================
-# telnetcpcd (untested)
-# - http://ftp.wayne.edu/kermit/sredird/telnetcpcd-1.09.tar.gz
-# - To get the signature [COM_PORT_OPTION] w/o data has to be sent.
-#=============================================================================
-# ser2net
-# - does not negotiate BINARY or COM_PORT_OPTION for his side but at least
-# acknowledges that the client activates these options
-# - The configuration may be that the server prints a banner. As this client
-# implementation does a flushInput on connect, this banner is hidden from
-# the user application.
-# - NOTIFY_MODEMSTATE: the poll interval of the server seems to be one
-# second.
-# - To get the signature [COM_PORT_OPTION 0] has to be sent.
-# - run a server: run ser2net daemon, in /etc/ser2net.conf:
-# 2000:telnet:0:/dev/ttyS0:9600 remctl banner
-##############################################################################
-
-# How to identify ports? pySerial might want to support other protocols in the
-# future, so lets use an URL scheme.
-# for RFC2217 compliant servers we will use this:
-# rfc2217://:[/option[/option...]]
-#
-# options:
-# - "debug" print diagnostic messages
-# - "ign_set_control": do not look at the answers to SET_CONTROL
-# - "poll_modem": issue NOTIFY_MODEMSTATE requests when CTS/DTR/RI/CD is read.
-# Without this option it expects that the server sends notifications
-# automatically on change (which most servers do and is according to the
-# RFC).
-# the order of the options is not relevant
-
-from serial.serialutil import *
-import time
-import struct
-import socket
-import threading
-import Queue
-import logging
-
-# port string is expected to be something like this:
-# rfc2217://host:port
-# host may be an IP or including domain, whatever.
-# port is 0...65535
-
-# map log level names to constants. used in fromURL()
-LOGGER_LEVELS = {
- 'debug': logging.DEBUG,
- 'info': logging.INFO,
- 'warning': logging.WARNING,
- 'error': logging.ERROR,
- }
-
-
-# telnet protocol characters
-IAC = to_bytes([255]) # Interpret As Command
-DONT = to_bytes([254])
-DO = to_bytes([253])
-WONT = to_bytes([252])
-WILL = to_bytes([251])
-IAC_DOUBLED = to_bytes([IAC, IAC])
-
-SE = to_bytes([240]) # Subnegotiation End
-NOP = to_bytes([241]) # No Operation
-DM = to_bytes([242]) # Data Mark
-BRK = to_bytes([243]) # Break
-IP = to_bytes([244]) # Interrupt process
-AO = to_bytes([245]) # Abort output
-AYT = to_bytes([246]) # Are You There
-EC = to_bytes([247]) # Erase Character
-EL = to_bytes([248]) # Erase Line
-GA = to_bytes([249]) # Go Ahead
-SB = to_bytes([250]) # Subnegotiation Begin
-
-# selected telnet options
-BINARY = to_bytes([0]) # 8-bit data path
-ECHO = to_bytes([1]) # echo
-SGA = to_bytes([3]) # suppress go ahead
-
-# RFC2217
-COM_PORT_OPTION = to_bytes([44])
-
-# Client to Access Server
-SET_BAUDRATE = to_bytes([1])
-SET_DATASIZE = to_bytes([2])
-SET_PARITY = to_bytes([3])
-SET_STOPSIZE = to_bytes([4])
-SET_CONTROL = to_bytes([5])
-NOTIFY_LINESTATE = to_bytes([6])
-NOTIFY_MODEMSTATE = to_bytes([7])
-FLOWCONTROL_SUSPEND = to_bytes([8])
-FLOWCONTROL_RESUME = to_bytes([9])
-SET_LINESTATE_MASK = to_bytes([10])
-SET_MODEMSTATE_MASK = to_bytes([11])
-PURGE_DATA = to_bytes([12])
-
-SERVER_SET_BAUDRATE = to_bytes([101])
-SERVER_SET_DATASIZE = to_bytes([102])
-SERVER_SET_PARITY = to_bytes([103])
-SERVER_SET_STOPSIZE = to_bytes([104])
-SERVER_SET_CONTROL = to_bytes([105])
-SERVER_NOTIFY_LINESTATE = to_bytes([106])
-SERVER_NOTIFY_MODEMSTATE = to_bytes([107])
-SERVER_FLOWCONTROL_SUSPEND = to_bytes([108])
-SERVER_FLOWCONTROL_RESUME = to_bytes([109])
-SERVER_SET_LINESTATE_MASK = to_bytes([110])
-SERVER_SET_MODEMSTATE_MASK = to_bytes([111])
-SERVER_PURGE_DATA = to_bytes([112])
-
-RFC2217_ANSWER_MAP = {
- SET_BAUDRATE: SERVER_SET_BAUDRATE,
- SET_DATASIZE: SERVER_SET_DATASIZE,
- SET_PARITY: SERVER_SET_PARITY,
- SET_STOPSIZE: SERVER_SET_STOPSIZE,
- SET_CONTROL: SERVER_SET_CONTROL,
- NOTIFY_LINESTATE: SERVER_NOTIFY_LINESTATE,
- NOTIFY_MODEMSTATE: SERVER_NOTIFY_MODEMSTATE,
- FLOWCONTROL_SUSPEND: SERVER_FLOWCONTROL_SUSPEND,
- FLOWCONTROL_RESUME: SERVER_FLOWCONTROL_RESUME,
- SET_LINESTATE_MASK: SERVER_SET_LINESTATE_MASK,
- SET_MODEMSTATE_MASK: SERVER_SET_MODEMSTATE_MASK,
- PURGE_DATA: SERVER_PURGE_DATA,
-}
-
-SET_CONTROL_REQ_FLOW_SETTING = to_bytes([0]) # Request Com Port Flow Control Setting (outbound/both)
-SET_CONTROL_USE_NO_FLOW_CONTROL = to_bytes([1]) # Use No Flow Control (outbound/both)
-SET_CONTROL_USE_SW_FLOW_CONTROL = to_bytes([2]) # Use XON/XOFF Flow Control (outbound/both)
-SET_CONTROL_USE_HW_FLOW_CONTROL = to_bytes([3]) # Use HARDWARE Flow Control (outbound/both)
-SET_CONTROL_REQ_BREAK_STATE = to_bytes([4]) # Request BREAK State
-SET_CONTROL_BREAK_ON = to_bytes([5]) # Set BREAK State ON
-SET_CONTROL_BREAK_OFF = to_bytes([6]) # Set BREAK State OFF
-SET_CONTROL_REQ_DTR = to_bytes([7]) # Request DTR Signal State
-SET_CONTROL_DTR_ON = to_bytes([8]) # Set DTR Signal State ON
-SET_CONTROL_DTR_OFF = to_bytes([9]) # Set DTR Signal State OFF
-SET_CONTROL_REQ_RTS = to_bytes([10]) # Request RTS Signal State
-SET_CONTROL_RTS_ON = to_bytes([11]) # Set RTS Signal State ON
-SET_CONTROL_RTS_OFF = to_bytes([12]) # Set RTS Signal State OFF
-SET_CONTROL_REQ_FLOW_SETTING_IN = to_bytes([13]) # Request Com Port Flow Control Setting (inbound)
-SET_CONTROL_USE_NO_FLOW_CONTROL_IN = to_bytes([14]) # Use No Flow Control (inbound)
-SET_CONTROL_USE_SW_FLOW_CONTOL_IN = to_bytes([15]) # Use XON/XOFF Flow Control (inbound)
-SET_CONTROL_USE_HW_FLOW_CONTOL_IN = to_bytes([16]) # Use HARDWARE Flow Control (inbound)
-SET_CONTROL_USE_DCD_FLOW_CONTROL = to_bytes([17]) # Use DCD Flow Control (outbound/both)
-SET_CONTROL_USE_DTR_FLOW_CONTROL = to_bytes([18]) # Use DTR Flow Control (inbound)
-SET_CONTROL_USE_DSR_FLOW_CONTROL = to_bytes([19]) # Use DSR Flow Control (outbound/both)
-
-LINESTATE_MASK_TIMEOUT = 128 # Time-out Error
-LINESTATE_MASK_SHIFTREG_EMPTY = 64 # Transfer Shift Register Empty
-LINESTATE_MASK_TRANSREG_EMPTY = 32 # Transfer Holding Register Empty
-LINESTATE_MASK_BREAK_DETECT = 16 # Break-detect Error
-LINESTATE_MASK_FRAMING_ERROR = 8 # Framing Error
-LINESTATE_MASK_PARTIY_ERROR = 4 # Parity Error
-LINESTATE_MASK_OVERRUN_ERROR = 2 # Overrun Error
-LINESTATE_MASK_DATA_READY = 1 # Data Ready
-
-MODEMSTATE_MASK_CD = 128 # Receive Line Signal Detect (also known as Carrier Detect)
-MODEMSTATE_MASK_RI = 64 # Ring Indicator
-MODEMSTATE_MASK_DSR = 32 # Data-Set-Ready Signal State
-MODEMSTATE_MASK_CTS = 16 # Clear-To-Send Signal State
-MODEMSTATE_MASK_CD_CHANGE = 8 # Delta Receive Line Signal Detect
-MODEMSTATE_MASK_RI_CHANGE = 4 # Trailing-edge Ring Detector
-MODEMSTATE_MASK_DSR_CHANGE = 2 # Delta Data-Set-Ready
-MODEMSTATE_MASK_CTS_CHANGE = 1 # Delta Clear-To-Send
-
-PURGE_RECEIVE_BUFFER = to_bytes([1]) # Purge access server receive data buffer
-PURGE_TRANSMIT_BUFFER = to_bytes([2]) # Purge access server transmit data buffer
-PURGE_BOTH_BUFFERS = to_bytes([3]) # Purge both the access server receive data buffer and the access server transmit data buffer
-
-
-RFC2217_PARITY_MAP = {
- PARITY_NONE: 1,
- PARITY_ODD: 2,
- PARITY_EVEN: 3,
- PARITY_MARK: 4,
- PARITY_SPACE: 5,
-}
-RFC2217_REVERSE_PARITY_MAP = dict((v,k) for k,v in RFC2217_PARITY_MAP.items())
-
-RFC2217_STOPBIT_MAP = {
- STOPBITS_ONE: 1,
- STOPBITS_ONE_POINT_FIVE: 3,
- STOPBITS_TWO: 2,
-}
-RFC2217_REVERSE_STOPBIT_MAP = dict((v,k) for k,v in RFC2217_STOPBIT_MAP.items())
-
-# Telnet filter states
-M_NORMAL = 0
-M_IAC_SEEN = 1
-M_NEGOTIATE = 2
-
-# TelnetOption and TelnetSubnegotiation states
-REQUESTED = 'REQUESTED'
-ACTIVE = 'ACTIVE'
-INACTIVE = 'INACTIVE'
-REALLY_INACTIVE = 'REALLY_INACTIVE'
-
-class TelnetOption(object):
- """Manage a single telnet option, keeps track of DO/DONT WILL/WONT."""
-
- def __init__(self, connection, name, option, send_yes, send_no, ack_yes, ack_no, initial_state, activation_callback=None):
- """Init option.
- :param connection: connection used to transmit answers
- :param name: a readable name for debug outputs
- :param send_yes: what to send when option is to be enabled.
- :param send_no: what to send when option is to be disabled.
- :param ack_yes: what to expect when remote agrees on option.
- :param ack_no: what to expect when remote disagrees on option.
- :param initial_state: options initialized with REQUESTED are tried to
- be enabled on startup. use INACTIVE for all others.
- """
- self.connection = connection
- self.name = name
- self.option = option
- self.send_yes = send_yes
- self.send_no = send_no
- self.ack_yes = ack_yes
- self.ack_no = ack_no
- self.state = initial_state
- self.active = False
- self.activation_callback = activation_callback
-
- def __repr__(self):
- """String for debug outputs"""
- return "%s:%s(%s)" % (self.name, self.active, self.state)
-
- def process_incoming(self, command):
- """A DO/DONT/WILL/WONT was received for this option, update state and
- answer when needed."""
- if command == self.ack_yes:
- if self.state is REQUESTED:
- self.state = ACTIVE
- self.active = True
- if self.activation_callback is not None:
- self.activation_callback()
- elif self.state is ACTIVE:
- pass
- elif self.state is INACTIVE:
- self.state = ACTIVE
- self.connection.telnetSendOption(self.send_yes, self.option)
- self.active = True
- if self.activation_callback is not None:
- self.activation_callback()
- elif self.state is REALLY_INACTIVE:
- self.connection.telnetSendOption(self.send_no, self.option)
- else:
- raise ValueError('option in illegal state %r' % self)
- elif command == self.ack_no:
- if self.state is REQUESTED:
- self.state = INACTIVE
- self.active = False
- elif self.state is ACTIVE:
- self.state = INACTIVE
- self.connection.telnetSendOption(self.send_no, self.option)
- self.active = False
- elif self.state is INACTIVE:
- pass
- elif self.state is REALLY_INACTIVE:
- pass
- else:
- raise ValueError('option in illegal state %r' % self)
-
-
-class TelnetSubnegotiation(object):
- """A object to handle subnegotiation of options. In this case actually
- sub-sub options for RFC 2217. It is used to track com port options."""
-
- def __init__(self, connection, name, option, ack_option=None):
- if ack_option is None: ack_option = option
- self.connection = connection
- self.name = name
- self.option = option
- self.value = None
- self.ack_option = ack_option
- self.state = INACTIVE
-
- def __repr__(self):
- """String for debug outputs."""
- return "%s:%s" % (self.name, self.state)
-
- def set(self, value):
- """request a change of the value. a request is sent to the server. if
- the client needs to know if the change is performed he has to check the
- state of this object."""
- self.value = value
- self.state = REQUESTED
- self.connection.rfc2217SendSubnegotiation(self.option, self.value)
- if self.connection.logger:
- self.connection.logger.debug("SB Requesting %s -> %r" % (self.name, self.value))
-
- def isReady(self):
- """check if answer from server has been received. when server rejects
- the change, raise a ValueError."""
- if self.state == REALLY_INACTIVE:
- raise ValueError("remote rejected value for option %r" % (self.name))
- return self.state == ACTIVE
- # add property to have a similar interface as TelnetOption
- active = property(isReady)
-
- def wait(self, timeout=3):
- """wait until the subnegotiation has been acknowledged or timeout. It
- can also throw a value error when the answer from the server does not
- match the value sent."""
- timeout_time = time.time() + timeout
- while time.time() < timeout_time:
- time.sleep(0.05) # prevent 100% CPU load
- if self.isReady():
- break
- else:
- raise SerialException("timeout while waiting for option %r" % (self.name))
-
- def checkAnswer(self, suboption):
- """check an incoming subnegotiation block. the parameter already has
- cut off the header like sub option number and com port option value."""
- if self.value == suboption[:len(self.value)]:
- self.state = ACTIVE
- else:
- # error propagation done in isReady
- self.state = REALLY_INACTIVE
- if self.connection.logger:
- self.connection.logger.debug("SB Answer %s -> %r -> %s" % (self.name, suboption, self.state))
-
-
-class RFC2217Serial(SerialBase):
- """Serial port implementation for RFC 2217 remote serial ports."""
-
- BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
- 9600, 19200, 38400, 57600, 115200)
-
- def open(self):
- """Open port with current settings. This may throw a SerialException
- if the port cannot be opened."""
- self.logger = None
- self._ignore_set_control_answer = False
- self._poll_modem_state = False
- self._network_timeout = 3
- if self._port is None:
- raise SerialException("Port must be configured before it can be used.")
- if self._isOpen:
- raise SerialException("Port is already open.")
- try:
- self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- self._socket.connect(self.fromURL(self.portstr))
- self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
- except Exception, msg:
- self._socket = None
- raise SerialException("Could not open port %s: %s" % (self.portstr, msg))
-
- self._socket.settimeout(5) # XXX good value?
-
- # use a thread save queue as buffer. it also simplifies implementing
- # the read timeout
- self._read_buffer = Queue.Queue()
- # to ensure that user writes does not interfere with internal
- # telnet/rfc2217 options establish a lock
- self._write_lock = threading.Lock()
- # name the following separately so that, below, a check can be easily done
- mandadory_options = [
- TelnetOption(self, 'we-BINARY', BINARY, WILL, WONT, DO, DONT, INACTIVE),
- TelnetOption(self, 'we-RFC2217', COM_PORT_OPTION, WILL, WONT, DO, DONT, REQUESTED),
- ]
- # all supported telnet options
- self._telnet_options = [
- TelnetOption(self, 'ECHO', ECHO, DO, DONT, WILL, WONT, REQUESTED),
- TelnetOption(self, 'we-SGA', SGA, WILL, WONT, DO, DONT, REQUESTED),
- TelnetOption(self, 'they-SGA', SGA, DO, DONT, WILL, WONT, REQUESTED),
- TelnetOption(self, 'they-BINARY', BINARY, DO, DONT, WILL, WONT, INACTIVE),
- TelnetOption(self, 'they-RFC2217', COM_PORT_OPTION, DO, DONT, WILL, WONT, REQUESTED),
- ] + mandadory_options
- # RFC 2217 specific states
- # COM port settings
- self._rfc2217_port_settings = {
- 'baudrate': TelnetSubnegotiation(self, 'baudrate', SET_BAUDRATE, SERVER_SET_BAUDRATE),
- 'datasize': TelnetSubnegotiation(self, 'datasize', SET_DATASIZE, SERVER_SET_DATASIZE),
- 'parity': TelnetSubnegotiation(self, 'parity', SET_PARITY, SERVER_SET_PARITY),
- 'stopsize': TelnetSubnegotiation(self, 'stopsize', SET_STOPSIZE, SERVER_SET_STOPSIZE),
- }
- # There are more subnegotiation objects, combine all in one dictionary
- # for easy access
- self._rfc2217_options = {
- 'purge': TelnetSubnegotiation(self, 'purge', PURGE_DATA, SERVER_PURGE_DATA),
- 'control': TelnetSubnegotiation(self, 'control', SET_CONTROL, SERVER_SET_CONTROL),
- }
- self._rfc2217_options.update(self._rfc2217_port_settings)
- # cache for line and modem states that the server sends to us
- self._linestate = 0
- self._modemstate = None
- self._modemstate_expires = 0
- # RFC 2217 flow control between server and client
- self._remote_suspend_flow = False
-
- self._thread = threading.Thread(target=self._telnetReadLoop)
- self._thread.setDaemon(True)
- self._thread.setName('pySerial RFC 2217 reader thread for %s' % (self._port,))
- self._thread.start()
-
- # negotiate Telnet/RFC 2217 -> send initial requests
- for option in self._telnet_options:
- if option.state is REQUESTED:
- self.telnetSendOption(option.send_yes, option.option)
- # now wait until important options are negotiated
- timeout_time = time.time() + self._network_timeout
- while time.time() < timeout_time:
- time.sleep(0.05) # prevent 100% CPU load
- if sum(o.active for o in mandadory_options) == len(mandadory_options):
- break
- else:
- raise SerialException("Remote does not seem to support RFC2217 or BINARY mode %r" % mandadory_options)
- if self.logger:
- self.logger.info("Negotiated options: %s" % self._telnet_options)
-
- # fine, go on, set RFC 2271 specific things
- self._reconfigurePort()
- # all things set up get, now a clean start
- self._isOpen = True
- if not self._rtscts:
- self.setRTS(True)
- self.setDTR(True)
- self.flushInput()
- self.flushOutput()
-
- def _reconfigurePort(self):
- """Set communication parameters on opened port."""
- if self._socket is None:
- raise SerialException("Can only operate on open ports")
-
- # if self._timeout != 0 and self._interCharTimeout is not None:
- # XXX
-
- if self._writeTimeout is not None:
- raise NotImplementedError('writeTimeout is currently not supported')
- # XXX
-
- # Setup the connection
- # to get good performance, all parameter changes are sent first...
- if not isinstance(self._baudrate, (int, long)) or not 0 < self._baudrate < 2**32:
- raise ValueError("invalid baudrate: %r" % (self._baudrate))
- self._rfc2217_port_settings['baudrate'].set(struct.pack('!I', self._baudrate))
- self._rfc2217_port_settings['datasize'].set(struct.pack('!B', self._bytesize))
- self._rfc2217_port_settings['parity'].set(struct.pack('!B', RFC2217_PARITY_MAP[self._parity]))
- self._rfc2217_port_settings['stopsize'].set(struct.pack('!B', RFC2217_STOPBIT_MAP[self._stopbits]))
-
- # and now wait until parameters are active
- items = self._rfc2217_port_settings.values()
- if self.logger:
- self.logger.debug("Negotiating settings: %s" % (items,))
- timeout_time = time.time() + self._network_timeout
- while time.time() < timeout_time:
- time.sleep(0.05) # prevent 100% CPU load
- if sum(o.active for o in items) == len(items):
- break
- else:
- raise SerialException("Remote does not accept parameter change (RFC2217): %r" % items)
- if self.logger:
- self.logger.info("Negotiated settings: %s" % (items,))
-
- if self._rtscts and self._xonxoff:
- raise ValueError('xonxoff and rtscts together are not supported')
- elif self._rtscts:
- self.rfc2217SetControl(SET_CONTROL_USE_HW_FLOW_CONTROL)
- elif self._xonxoff:
- self.rfc2217SetControl(SET_CONTROL_USE_SW_FLOW_CONTROL)
- else:
- self.rfc2217SetControl(SET_CONTROL_USE_NO_FLOW_CONTROL)
-
- def close(self):
- """Close port"""
- if self._isOpen:
- if self._socket:
- try:
- self._socket.shutdown(socket.SHUT_RDWR)
- self._socket.close()
- except:
- # ignore errors.
- pass
- self._socket = None
- if self._thread:
- self._thread.join()
- self._isOpen = False
- # in case of quick reconnects, give the server some time
- time.sleep(0.3)
-
- def makeDeviceName(self, port):
- raise SerialException("there is no sensible way to turn numbers into URLs")
-
- def fromURL(self, url):
- """extract host and port from an URL string"""
- if url.lower().startswith("rfc2217://"): url = url[10:]
- try:
- # is there a "path" (our options)?
- if '/' in url:
- # cut away options
- url, options = url.split('/', 1)
- # process options now, directly altering self
- for option in options.split('/'):
- if '=' in option:
- option, value = option.split('=', 1)
- else:
- value = None
- if option == 'logging':
- logging.basicConfig() # XXX is that good to call it here?
- self.logger = logging.getLogger('pySerial.rfc2217')
- self.logger.setLevel(LOGGER_LEVELS[value])
- self.logger.debug('enabled logging')
- elif option == 'ign_set_control':
- self._ignore_set_control_answer = True
- elif option == 'poll_modem':
- self._poll_modem_state = True
- elif option == 'timeout':
- self._network_timeout = float(value)
- else:
- raise ValueError('unknown option: %r' % (option,))
- # get host and port
- host, port = url.split(':', 1) # may raise ValueError because of unpacking
- port = int(port) # and this if it's not a number
- if not 0 <= port < 65536: raise ValueError("port not in range 0...65535")
- except ValueError, e:
- raise SerialException('expected a string in the form "[rfc2217://]:[/option[/option...]]": %s' % e)
- return (host, port)
-
- # - - - - - - - - - - - - - - - - - - - - - - - -
-
- def inWaiting(self):
- """Return the number of characters currently in the input buffer."""
- if not self._isOpen: raise portNotOpenError
- return self._read_buffer.qsize()
-
- def read(self, size=1):
- """Read size bytes from the serial port. If a timeout is set it may
- return less characters as requested. With no timeout it will block
- until the requested number of bytes is read."""
- if not self._isOpen: raise portNotOpenError
- data = bytearray()
- try:
- while len(data) < size:
- if self._thread is None:
- raise SerialException('connection failed (reader thread died)')
- data.append(self._read_buffer.get(True, self._timeout))
- except Queue.Empty: # -> timeout
- pass
- return bytes(data)
-
- def write(self, data):
- """Output the given string over the serial port. Can block if the
- connection is blocked. May raise SerialException if the connection is
- closed."""
- if not self._isOpen: raise portNotOpenError
- self._write_lock.acquire()
- try:
- try:
- self._socket.sendall(data.replace(IAC, IAC_DOUBLED))
- except socket.error, e:
- raise SerialException("connection failed (socket error): %s" % e) # XXX what exception if socket connection fails
- finally:
- self._write_lock.release()
- return len(data)
-
- def flushInput(self):
- """Clear input buffer, discarding all that is in the buffer."""
- if not self._isOpen: raise portNotOpenError
- self.rfc2217SendPurge(PURGE_RECEIVE_BUFFER)
- # empty read buffer
- while self._read_buffer.qsize():
- self._read_buffer.get(False)
-
- def flushOutput(self):
- """Clear output buffer, aborting the current output and
- discarding all that is in the buffer."""
- if not self._isOpen: raise portNotOpenError
- self.rfc2217SendPurge(PURGE_TRANSMIT_BUFFER)
-
- def sendBreak(self, duration=0.25):
- """Send break condition. Timed, returns to idle state after given
- duration."""
- if not self._isOpen: raise portNotOpenError
- self.setBreak(True)
- time.sleep(duration)
- self.setBreak(False)
-
- def setBreak(self, level=True):
- """Set break: Controls TXD. When active, to transmitting is
- possible."""
- if not self._isOpen: raise portNotOpenError
- if self.logger:
- self.logger.info('set BREAK to %s' % ('inactive', 'active')[bool(level)])
- if level:
- self.rfc2217SetControl(SET_CONTROL_BREAK_ON)
- else:
- self.rfc2217SetControl(SET_CONTROL_BREAK_OFF)
-
- def setRTS(self, level=True):
- """Set terminal status line: Request To Send."""
- if not self._isOpen: raise portNotOpenError
- if self.logger:
- self.logger.info('set RTS to %s' % ('inactive', 'active')[bool(level)])
- if level:
- self.rfc2217SetControl(SET_CONTROL_RTS_ON)
- else:
- self.rfc2217SetControl(SET_CONTROL_RTS_OFF)
-
- def setDTR(self, level=True):
- """Set terminal status line: Data Terminal Ready."""
- if not self._isOpen: raise portNotOpenError
- if self.logger:
- self.logger.info('set DTR to %s' % ('inactive', 'active')[bool(level)])
- if level:
- self.rfc2217SetControl(SET_CONTROL_DTR_ON)
- else:
- self.rfc2217SetControl(SET_CONTROL_DTR_OFF)
-
- def getCTS(self):
- """Read terminal status line: Clear To Send."""
- if not self._isOpen: raise portNotOpenError
- return bool(self.getModemState() & MODEMSTATE_MASK_CTS)
-
- def getDSR(self):
- """Read terminal status line: Data Set Ready."""
- if not self._isOpen: raise portNotOpenError
- return bool(self.getModemState() & MODEMSTATE_MASK_DSR)
-
- def getRI(self):
- """Read terminal status line: Ring Indicator."""
- if not self._isOpen: raise portNotOpenError
- return bool(self.getModemState() & MODEMSTATE_MASK_RI)
-
- def getCD(self):
- """Read terminal status line: Carrier Detect."""
- if not self._isOpen: raise portNotOpenError
- return bool(self.getModemState() & MODEMSTATE_MASK_CD)
-
- # - - - platform specific - - -
- # None so far
-
- # - - - RFC2217 specific - - -
-
- def _telnetReadLoop(self):
- """read loop for the socket."""
- mode = M_NORMAL
- suboption = None
- try:
- while self._socket is not None:
- try:
- data = self._socket.recv(1024)
- except socket.timeout:
- # just need to get out of recv form time to time to check if
- # still alive
- continue
- except socket.error, e:
- # connection fails -> terminate loop
- if self.logger:
- self.logger.debug("socket error in reader thread: %s" % (e,))
- break
- if not data: break # lost connection
- for byte in data:
- if mode == M_NORMAL:
- # interpret as command or as data
- if byte == IAC:
- mode = M_IAC_SEEN
- else:
- # store data in read buffer or sub option buffer
- # depending on state
- if suboption is not None:
- suboption.append(byte)
- else:
- self._read_buffer.put(byte)
- elif mode == M_IAC_SEEN:
- if byte == IAC:
- # interpret as command doubled -> insert character
- # itself
- if suboption is not None:
- suboption.append(IAC)
- else:
- self._read_buffer.put(IAC)
- mode = M_NORMAL
- elif byte == SB:
- # sub option start
- suboption = bytearray()
- mode = M_NORMAL
- elif byte == SE:
- # sub option end -> process it now
- self._telnetProcessSubnegotiation(bytes(suboption))
- suboption = None
- mode = M_NORMAL
- elif byte in (DO, DONT, WILL, WONT):
- # negotiation
- telnet_command = byte
- mode = M_NEGOTIATE
- else:
- # other telnet commands
- self._telnetProcessCommand(byte)
- mode = M_NORMAL
- elif mode == M_NEGOTIATE: # DO, DONT, WILL, WONT was received, option now following
- self._telnetNegotiateOption(telnet_command, byte)
- mode = M_NORMAL
- finally:
- self._thread = None
- if self.logger:
- self.logger.debug("read thread terminated")
-
- # - incoming telnet commands and options
-
- def _telnetProcessCommand(self, command):
- """Process commands other than DO, DONT, WILL, WONT."""
- # Currently none. RFC2217 only uses negotiation and subnegotiation.
- if self.logger:
- self.logger.warning("ignoring Telnet command: %r" % (command,))
-
- def _telnetNegotiateOption(self, command, option):
- """Process incoming DO, DONT, WILL, WONT."""
- # check our registered telnet options and forward command to them
- # they know themselves if they have to answer or not
- known = False
- for item in self._telnet_options:
- # can have more than one match! as some options are duplicated for
- # 'us' and 'them'
- if item.option == option:
- item.process_incoming(command)
- known = True
- if not known:
- # handle unknown options
- # only answer to positive requests and deny them
- if command == WILL or command == DO:
- self.telnetSendOption((command == WILL and DONT or WONT), option)
- if self.logger:
- self.logger.warning("rejected Telnet option: %r" % (option,))
-
-
- def _telnetProcessSubnegotiation(self, suboption):
- """Process subnegotiation, the data between IAC SB and IAC SE."""
- if suboption[0:1] == COM_PORT_OPTION:
- if suboption[1:2] == SERVER_NOTIFY_LINESTATE and len(suboption) >= 3:
- self._linestate = ord(suboption[2:3]) # ensure it is a number
- if self.logger:
- self.logger.info("NOTIFY_LINESTATE: %s" % self._linestate)
- elif suboption[1:2] == SERVER_NOTIFY_MODEMSTATE and len(suboption) >= 3:
- self._modemstate = ord(suboption[2:3]) # ensure it is a number
- if self.logger:
- self.logger.info("NOTIFY_MODEMSTATE: %s" % self._modemstate)
- # update time when we think that a poll would make sense
- self._modemstate_expires = time.time() + 0.3
- elif suboption[1:2] == FLOWCONTROL_SUSPEND:
- self._remote_suspend_flow = True
- elif suboption[1:2] == FLOWCONTROL_RESUME:
- self._remote_suspend_flow = False
- else:
- for item in self._rfc2217_options.values():
- if item.ack_option == suboption[1:2]:
- #~ print "processing COM_PORT_OPTION: %r" % list(suboption[1:])
- item.checkAnswer(bytes(suboption[2:]))
- break
- else:
- if self.logger:
- self.logger.warning("ignoring COM_PORT_OPTION: %r" % (suboption,))
- else:
- if self.logger:
- self.logger.warning("ignoring subnegotiation: %r" % (suboption,))
-
- # - outgoing telnet commands and options
-
- def _internal_raw_write(self, data):
- """internal socket write with no data escaping. used to send telnet stuff."""
- self._write_lock.acquire()
- try:
- self._socket.sendall(data)
- finally:
- self._write_lock.release()
-
- def telnetSendOption(self, action, option):
- """Send DO, DONT, WILL, WONT."""
- self._internal_raw_write(to_bytes([IAC, action, option]))
-
- def rfc2217SendSubnegotiation(self, option, value=''):
- """Subnegotiation of RFC2217 parameters."""
- value = value.replace(IAC, IAC_DOUBLED)
- self._internal_raw_write(to_bytes([IAC, SB, COM_PORT_OPTION, option] + list(value) + [IAC, SE]))
-
- def rfc2217SendPurge(self, value):
- item = self._rfc2217_options['purge']
- item.set(value) # transmit desired purge type
- item.wait(self._network_timeout) # wait for acknowledge from the server
-
- def rfc2217SetControl(self, value):
- item = self._rfc2217_options['control']
- item.set(value) # transmit desired control type
- if self._ignore_set_control_answer:
- # answers are ignored when option is set. compatibility mode for
- # servers that answer, but not the expected one... (or no answer
- # at all) i.e. sredird
- time.sleep(0.1) # this helps getting the unit tests passed
- else:
- item.wait(self._network_timeout) # wait for acknowledge from the server
-
- def rfc2217FlowServerReady(self):
- """check if server is ready to receive data. block for some time when
- not."""
- #~ if self._remote_suspend_flow:
- #~ wait---
-
- def getModemState(self):
- """get last modem state (cached value. if value is "old", request a new
- one. this cache helps that we don't issue to many requests when e.g. all
- status lines, one after the other is queried by te user (getCTS, getDSR
- etc.)"""
- # active modem state polling enabled? is the value fresh enough?
- if self._poll_modem_state and self._modemstate_expires < time.time():
- if self.logger:
- self.logger.debug('polling modem state')
- # when it is older, request an update
- self.rfc2217SendSubnegotiation(NOTIFY_MODEMSTATE)
- timeout_time = time.time() + self._network_timeout
- while time.time() < timeout_time:
- time.sleep(0.05) # prevent 100% CPU load
- # when expiration time is updated, it means that there is a new
- # value
- if self._modemstate_expires > time.time():
- if self.logger:
- self.logger.warning('poll for modem state failed')
- break
- # even when there is a timeout, do not generate an error just
- # return the last known value. this way we can support buggy
- # servers that do not respond to polls, but send automatic
- # updates.
- if self._modemstate is not None:
- if self.logger:
- self.logger.debug('using cached modem state')
- return self._modemstate
- else:
- # never received a notification from the server
- raise SerialException("remote sends no NOTIFY_MODEMSTATE")
-
-
-# assemble Serial class with the platform specific implementation and the base
-# for file-like behavior. for Python 2.6 and newer, that provide the new I/O
-# library, derive from io.RawIOBase
-try:
- import io
-except ImportError:
- # classic version with our own file-like emulation
- class Serial(RFC2217Serial, FileLike):
- pass
-else:
- # io library present
- class Serial(RFC2217Serial, io.RawIOBase):
- pass
-
-
-#############################################################################
-# The following is code that helps implementing an RFC 2217 server.
-
-class PortManager(object):
- """This class manages the state of Telnet and RFC 2217. It needs a serial
- instance and a connection to work with. Connection is expected to implement
- a (thread safe) write function, that writes the string to the network."""
-
- def __init__(self, serial_port, connection, logger=None):
- self.serial = serial_port
- self.connection = connection
- self.logger = logger
- self._client_is_rfc2217 = False
-
- # filter state machine
- self.mode = M_NORMAL
- self.suboption = None
- self.telnet_command = None
-
- # states for modem/line control events
- self.modemstate_mask = 255
- self.last_modemstate = None
- self.linstate_mask = 0
-
- # all supported telnet options
- self._telnet_options = [
- TelnetOption(self, 'ECHO', ECHO, WILL, WONT, DO, DONT, REQUESTED),
- TelnetOption(self, 'we-SGA', SGA, WILL, WONT, DO, DONT, REQUESTED),
- TelnetOption(self, 'they-SGA', SGA, DO, DONT, WILL, WONT, INACTIVE),
- TelnetOption(self, 'we-BINARY', BINARY, WILL, WONT, DO, DONT, INACTIVE),
- TelnetOption(self, 'they-BINARY', BINARY, DO, DONT, WILL, WONT, REQUESTED),
- TelnetOption(self, 'we-RFC2217', COM_PORT_OPTION, WILL, WONT, DO, DONT, REQUESTED, self._client_ok),
- TelnetOption(self, 'they-RFC2217', COM_PORT_OPTION, DO, DONT, WILL, WONT, INACTIVE, self._client_ok),
- ]
-
- # negotiate Telnet/RFC2217 -> send initial requests
- if self.logger:
- self.logger.debug("requesting initial Telnet/RFC 2217 options")
- for option in self._telnet_options:
- if option.state is REQUESTED:
- self.telnetSendOption(option.send_yes, option.option)
- # issue 1st modem state notification
-
- def _client_ok(self):
- """callback of telnet option. it gets called when option is activated.
- this one here is used to detect when the client agrees on RFC 2217. a
- flag is set so that other functions like check_modem_lines know if the
- client is ok."""
- # The callback is used for we and they so if one party agrees, we're
- # already happy. it seems not all servers do the negotiation correctly
- # and i guess there are incorrect clients too.. so be happy if client
- # answers one or the other positively.
- self._client_is_rfc2217 = True
- if self.logger:
- self.logger.info("client accepts RFC 2217")
- # this is to ensure that the client gets a notification, even if there
- # was no change
- self.check_modem_lines(force_notification=True)
-
- # - outgoing telnet commands and options
-
- def telnetSendOption(self, action, option):
- """Send DO, DONT, WILL, WONT."""
- self.connection.write(to_bytes([IAC, action, option]))
-
- def rfc2217SendSubnegotiation(self, option, value=''):
- """Subnegotiation of RFC 2217 parameters."""
- value = value.replace(IAC, IAC_DOUBLED)
- self.connection.write(to_bytes([IAC, SB, COM_PORT_OPTION, option] + list(value) + [IAC, SE]))
-
- # - check modem lines, needs to be called periodically from user to
- # establish polling
-
- def check_modem_lines(self, force_notification=False):
- modemstate = (
- (self.serial.getCTS() and MODEMSTATE_MASK_CTS) |
- (self.serial.getDSR() and MODEMSTATE_MASK_DSR) |
- (self.serial.getRI() and MODEMSTATE_MASK_RI) |
- (self.serial.getCD() and MODEMSTATE_MASK_CD)
- )
- # check what has changed
- deltas = modemstate ^ (self.last_modemstate or 0) # when last is None -> 0
- if deltas & MODEMSTATE_MASK_CTS:
- modemstate |= MODEMSTATE_MASK_CTS_CHANGE
- if deltas & MODEMSTATE_MASK_DSR:
- modemstate |= MODEMSTATE_MASK_DSR_CHANGE
- if deltas & MODEMSTATE_MASK_RI:
- modemstate |= MODEMSTATE_MASK_RI_CHANGE
- if deltas & MODEMSTATE_MASK_CD:
- modemstate |= MODEMSTATE_MASK_CD_CHANGE
- # if new state is different and the mask allows this change, send
- # notification. suppress notifications when client is not rfc2217
- if modemstate != self.last_modemstate or force_notification:
- if (self._client_is_rfc2217 and (modemstate & self.modemstate_mask)) or force_notification:
- self.rfc2217SendSubnegotiation(
- SERVER_NOTIFY_MODEMSTATE,
- to_bytes([modemstate & self.modemstate_mask])
- )
- if self.logger:
- self.logger.info("NOTIFY_MODEMSTATE: %s" % (modemstate,))
- # save last state, but forget about deltas.
- # otherwise it would also notify about changing deltas which is
- # probably not very useful
- self.last_modemstate = modemstate & 0xf0
-
- # - outgoing data escaping
-
- def escape(self, data):
- """this generator function is for the user. all outgoing data has to be
- properly escaped, so that no IAC character in the data stream messes up
- the Telnet state machine in the server.
-
- socket.sendall(escape(data))
- """
- for byte in data:
- if byte == IAC:
- yield IAC
- yield IAC
- else:
- yield byte
-
- # - incoming data filter
-
- def filter(self, data):
- """handle a bunch of incoming bytes. this is a generator. it will yield
- all characters not of interest for Telnet/RFC 2217.
-
- The idea is that the reader thread pushes data from the socket through
- this filter:
-
- for byte in filter(socket.recv(1024)):
- # do things like CR/LF conversion/whatever
- # and write data to the serial port
- serial.write(byte)
-
- (socket error handling code left as exercise for the reader)
- """
- for byte in data:
- if self.mode == M_NORMAL:
- # interpret as command or as data
- if byte == IAC:
- self.mode = M_IAC_SEEN
- else:
- # store data in sub option buffer or pass it to our
- # consumer depending on state
- if self.suboption is not None:
- self.suboption.append(byte)
- else:
- yield byte
- elif self.mode == M_IAC_SEEN:
- if byte == IAC:
- # interpret as command doubled -> insert character
- # itself
- if self.suboption is not None:
- self.suboption.append(byte)
- else:
- yield byte
- self.mode = M_NORMAL
- elif byte == SB:
- # sub option start
- self.suboption = bytearray()
- self.mode = M_NORMAL
- elif byte == SE:
- # sub option end -> process it now
- self._telnetProcessSubnegotiation(bytes(self.suboption))
- self.suboption = None
- self.mode = M_NORMAL
- elif byte in (DO, DONT, WILL, WONT):
- # negotiation
- self.telnet_command = byte
- self.mode = M_NEGOTIATE
- else:
- # other telnet commands
- self._telnetProcessCommand(byte)
- self.mode = M_NORMAL
- elif self.mode == M_NEGOTIATE: # DO, DONT, WILL, WONT was received, option now following
- self._telnetNegotiateOption(self.telnet_command, byte)
- self.mode = M_NORMAL
-
- # - incoming telnet commands and options
-
- def _telnetProcessCommand(self, command):
- """Process commands other than DO, DONT, WILL, WONT."""
- # Currently none. RFC2217 only uses negotiation and subnegotiation.
- if self.logger:
- self.logger.warning("ignoring Telnet command: %r" % (command,))
-
- def _telnetNegotiateOption(self, command, option):
- """Process incoming DO, DONT, WILL, WONT."""
- # check our registered telnet options and forward command to them
- # they know themselves if they have to answer or not
- known = False
- for item in self._telnet_options:
- # can have more than one match! as some options are duplicated for
- # 'us' and 'them'
- if item.option == option:
- item.process_incoming(command)
- known = True
- if not known:
- # handle unknown options
- # only answer to positive requests and deny them
- if command == WILL or command == DO:
- self.telnetSendOption((command == WILL and DONT or WONT), option)
- if self.logger:
- self.logger.warning("rejected Telnet option: %r" % (option,))
-
-
- def _telnetProcessSubnegotiation(self, suboption):
- """Process subnegotiation, the data between IAC SB and IAC SE."""
- if suboption[0:1] == COM_PORT_OPTION:
- if self.logger:
- self.logger.debug('received COM_PORT_OPTION: %r' % (suboption,))
- if suboption[1:2] == SET_BAUDRATE:
- backup = self.serial.baudrate
- try:
- (self.serial.baudrate,) = struct.unpack("!I", suboption[2:6])
- except ValueError, e:
- if self.logger:
- self.logger.error("failed to set baud rate: %s" % (e,))
- self.serial.baudrate = backup
- else:
- if self.logger:
- self.logger.info("changed baud rate: %s" % (self.serial.baudrate,))
- self.rfc2217SendSubnegotiation(SERVER_SET_BAUDRATE, struct.pack("!I", self.serial.baudrate))
- elif suboption[1:2] == SET_DATASIZE:
- backup = self.serial.bytesize
- try:
- (self.serial.bytesize,) = struct.unpack("!B", suboption[2:3])
- except ValueError, e:
- if self.logger:
- self.logger.error("failed to set data size: %s" % (e,))
- self.serial.bytesize = backup
- else:
- if self.logger:
- self.logger.info("changed data size: %s" % (self.serial.bytesize,))
- self.rfc2217SendSubnegotiation(SERVER_SET_DATASIZE, struct.pack("!B", self.serial.bytesize))
- elif suboption[1:2] == SET_PARITY:
- backup = self.serial.parity
- try:
- self.serial.parity = RFC2217_REVERSE_PARITY_MAP[struct.unpack("!B", suboption[2:3])[0]]
- except ValueError, e:
- if self.logger:
- self.logger.error("failed to set parity: %s" % (e,))
- self.serial.parity = backup
- else:
- if self.logger:
- self.logger.info("changed parity: %s" % (self.serial.parity,))
- self.rfc2217SendSubnegotiation(
- SERVER_SET_PARITY,
- struct.pack("!B", RFC2217_PARITY_MAP[self.serial.parity])
- )
- elif suboption[1:2] == SET_STOPSIZE:
- backup = self.serial.stopbits
- try:
- self.serial.stopbits = RFC2217_REVERSE_STOPBIT_MAP[struct.unpack("!B", suboption[2:3])[0]]
- except ValueError, e:
- if self.logger:
- self.logger.error("failed to set stop bits: %s" % (e,))
- self.serial.stopbits = backup
- else:
- if self.logger:
- self.logger.info("changed stop bits: %s" % (self.serial.stopbits,))
- self.rfc2217SendSubnegotiation(
- SERVER_SET_STOPSIZE,
- struct.pack("!B", RFC2217_STOPBIT_MAP[self.serial.stopbits])
- )
- elif suboption[1:2] == SET_CONTROL:
- if suboption[2:3] == SET_CONTROL_REQ_FLOW_SETTING:
- if self.serial.xonxoff:
- self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_USE_SW_FLOW_CONTROL)
- elif self.serial.rtscts:
- self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_USE_HW_FLOW_CONTROL)
- else:
- self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_USE_NO_FLOW_CONTROL)
- elif suboption[2:3] == SET_CONTROL_USE_NO_FLOW_CONTROL:
- self.serial.xonxoff = False
- self.serial.rtscts = False
- if self.logger:
- self.logger.info("changed flow control to None")
- self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_USE_NO_FLOW_CONTROL)
- elif suboption[2:3] == SET_CONTROL_USE_SW_FLOW_CONTROL:
- self.serial.xonxoff = True
- if self.logger:
- self.logger.info("changed flow control to XON/XOFF")
- self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_USE_SW_FLOW_CONTROL)
- elif suboption[2:3] == SET_CONTROL_USE_HW_FLOW_CONTROL:
- self.serial.rtscts = True
- if self.logger:
- self.logger.info("changed flow control to RTS/CTS")
- self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_USE_HW_FLOW_CONTROL)
- elif suboption[2:3] == SET_CONTROL_REQ_BREAK_STATE:
- if self.logger:
- self.logger.warning("requested break state - not implemented")
- pass # XXX needs cached value
- elif suboption[2:3] == SET_CONTROL_BREAK_ON:
- self.serial.setBreak(True)
- if self.logger:
- self.logger.info("changed BREAK to active")
- self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_BREAK_ON)
- elif suboption[2:3] == SET_CONTROL_BREAK_OFF:
- self.serial.setBreak(False)
- if self.logger:
- self.logger.info("changed BREAK to inactive")
- self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_BREAK_OFF)
- elif suboption[2:3] == SET_CONTROL_REQ_DTR:
- if self.logger:
- self.logger.warning("requested DTR state - not implemented")
- pass # XXX needs cached value
- elif suboption[2:3] == SET_CONTROL_DTR_ON:
- self.serial.setDTR(True)
- if self.logger:
- self.logger.info("changed DTR to active")
- self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_DTR_ON)
- elif suboption[2:3] == SET_CONTROL_DTR_OFF:
- self.serial.setDTR(False)
- if self.logger:
- self.logger.info("changed DTR to inactive")
- self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_DTR_OFF)
- elif suboption[2:3] == SET_CONTROL_REQ_RTS:
- if self.logger:
- self.logger.warning("requested RTS state - not implemented")
- pass # XXX needs cached value
- #~ self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_RTS_ON)
- elif suboption[2:3] == SET_CONTROL_RTS_ON:
- self.serial.setRTS(True)
- if self.logger:
- self.logger.info("changed RTS to active")
- self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_RTS_ON)
- elif suboption[2:3] == SET_CONTROL_RTS_OFF:
- self.serial.setRTS(False)
- if self.logger:
- self.logger.info("changed RTS to inactive")
- self.rfc2217SendSubnegotiation(SERVER_SET_CONTROL, SET_CONTROL_RTS_OFF)
- #~ elif suboption[2:3] == SET_CONTROL_REQ_FLOW_SETTING_IN:
- #~ elif suboption[2:3] == SET_CONTROL_USE_NO_FLOW_CONTROL_IN:
- #~ elif suboption[2:3] == SET_CONTROL_USE_SW_FLOW_CONTOL_IN:
- #~ elif suboption[2:3] == SET_CONTROL_USE_HW_FLOW_CONTOL_IN:
- #~ elif suboption[2:3] == SET_CONTROL_USE_DCD_FLOW_CONTROL:
- #~ elif suboption[2:3] == SET_CONTROL_USE_DTR_FLOW_CONTROL:
- #~ elif suboption[2:3] == SET_CONTROL_USE_DSR_FLOW_CONTROL:
- elif suboption[1:2] == NOTIFY_LINESTATE:
- # client polls for current state
- self.rfc2217SendSubnegotiation(
- SERVER_NOTIFY_LINESTATE,
- to_bytes([0]) # sorry, nothing like that implemented
- )
- elif suboption[1:2] == NOTIFY_MODEMSTATE:
- if self.logger:
- self.logger.info("request for modem state")
- # client polls for current state
- self.check_modem_lines(force_notification=True)
- elif suboption[1:2] == FLOWCONTROL_SUSPEND:
- if self.logger:
- self.logger.info("suspend")
- self._remote_suspend_flow = True
- elif suboption[1:2] == FLOWCONTROL_RESUME:
- if self.logger:
- self.logger.info("resume")
- self._remote_suspend_flow = False
- elif suboption[1:2] == SET_LINESTATE_MASK:
- self.linstate_mask = ord(suboption[2:3]) # ensure it is a number
- if self.logger:
- self.logger.info("line state mask: 0x%02x" % (self.linstate_mask,))
- elif suboption[1:2] == SET_MODEMSTATE_MASK:
- self.modemstate_mask = ord(suboption[2:3]) # ensure it is a number
- if self.logger:
- self.logger.info("modem state mask: 0x%02x" % (self.modemstate_mask,))
- elif suboption[1:2] == PURGE_DATA:
- if suboption[2:3] == PURGE_RECEIVE_BUFFER:
- self.serial.flushInput()
- if self.logger:
- self.logger.info("purge in")
- self.rfc2217SendSubnegotiation(SERVER_PURGE_DATA, PURGE_RECEIVE_BUFFER)
- elif suboption[2:3] == PURGE_TRANSMIT_BUFFER:
- self.serial.flushOutput()
- if self.logger:
- self.logger.info("purge out")
- self.rfc2217SendSubnegotiation(SERVER_PURGE_DATA, PURGE_TRANSMIT_BUFFER)
- elif suboption[2:3] == PURGE_BOTH_BUFFERS:
- self.serial.flushInput()
- self.serial.flushOutput()
- if self.logger:
- self.logger.info("purge both")
- self.rfc2217SendSubnegotiation(SERVER_PURGE_DATA, PURGE_BOTH_BUFFERS)
- else:
- if self.logger:
- self.logger.error("undefined PURGE_DATA: %r" % list(suboption[2:]))
- else:
- if self.logger:
- self.logger.error("undefined COM_PORT_OPTION: %r" % list(suboption[1:]))
- else:
- if self.logger:
- self.logger.warning("unknown subnegotiation: %r" % (suboption,))
-
-
-# simple client test
-if __name__ == '__main__':
- import sys
- s = Serial('rfc2217://localhost:7000', 115200)
- sys.stdout.write('%s\n' % s)
-
- #~ s.baudrate = 1898
-
- sys.stdout.write("write...\n")
- s.write("hello\n")
- s.flush()
- sys.stdout.write("read: %s\n" % s.read(5))
-
- #~ s.baudrate = 19200
- #~ s.databits = 7
- s.close()
diff --git a/python-serial/pyserial/build/lib/serial/serialcli.py b/python-serial/pyserial/build/lib/serial/serialcli.py
deleted file mode 100644
index 2c811f5..0000000
--- a/python-serial/pyserial/build/lib/serial/serialcli.py
+++ /dev/null
@@ -1,273 +0,0 @@
-#! python
-# Python Serial Port Extension for Win32, Linux, BSD, Jython and .NET/Mono
-# serial driver for .NET/Mono (IronPython), .NET >= 2
-# see __init__.py
-#
-# (C) 2008 Chris Liechti
-# this is distributed under a free software license, see license.txt
-
-import clr
-import System
-import System.IO.Ports
-from serial.serialutil import *
-
-
-def device(portnum):
- """Turn a port number into a device name"""
- return System.IO.Ports.SerialPort.GetPortNames()[portnum]
-
-
-# must invoke function with byte array, make a helper to convert strings
-# to byte arrays
-sab = System.Array[System.Byte]
-def as_byte_array(string):
- return sab([ord(x) for x in string]) # XXX will require adaption when run with a 3.x compatible IronPython
-
-class IronSerial(SerialBase):
- """Serial port implemenation for .NET/Mono."""
-
- BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
- 9600, 19200, 38400, 57600, 115200)
-
- def open(self):
- """Open port with current settings. This may throw a SerialException
- if the port cannot be opened."""
- if self._port is None:
- raise SerialException("Port must be configured before it can be used.")
- if self._isOpen:
- raise SerialException("Port is already open.")
- try:
- self._port_handle = System.IO.Ports.SerialPort(self.portstr)
- except Exception, msg:
- self._port_handle = None
- raise SerialException("could not open port %s: %s" % (self.portstr, msg))
-
- self._reconfigurePort()
- self._port_handle.Open()
- self._isOpen = True
- if not self._rtscts:
- self.setRTS(True)
- self.setDTR(True)
- self.flushInput()
- self.flushOutput()
-
- def _reconfigurePort(self):
- """Set communication parameters on opened port."""
- if not self._port_handle:
- raise SerialException("Can only operate on a valid port handle")
-
- #~ self._port_handle.ReceivedBytesThreshold = 1
-
- if self._timeout is None:
- self._port_handle.ReadTimeout = System.IO.Ports.SerialPort.InfiniteTimeout
- else:
- self._port_handle.ReadTimeout = int(self._timeout*1000)
-
- # if self._timeout != 0 and self._interCharTimeout is not None:
- # timeouts = (int(self._interCharTimeout * 1000),) + timeouts[1:]
-
- if self._writeTimeout is None:
- self._port_handle.WriteTimeout = System.IO.Ports.SerialPort.InfiniteTimeout
- else:
- self._port_handle.WriteTimeout = int(self._writeTimeout*1000)
-
-
- # Setup the connection info.
- try:
- self._port_handle.BaudRate = self._baudrate
- except IOError, e:
- # catch errors from illegal baudrate settings
- raise ValueError(str(e))
-
- if self._bytesize == FIVEBITS:
- self._port_handle.DataBits = 5
- elif self._bytesize == SIXBITS:
- self._port_handle.DataBits = 6
- elif self._bytesize == SEVENBITS:
- self._port_handle.DataBits = 7
- elif self._bytesize == EIGHTBITS:
- self._port_handle.DataBits = 8
- else:
- raise ValueError("Unsupported number of data bits: %r" % self._bytesize)
-
- if self._parity == PARITY_NONE:
- self._port_handle.Parity = getattr(System.IO.Ports.Parity, 'None') # reserved keyword in Py3k
- elif self._parity == PARITY_EVEN:
- self._port_handle.Parity = System.IO.Ports.Parity.Even
- elif self._parity == PARITY_ODD:
- self._port_handle.Parity = System.IO.Ports.Parity.Odd
- elif self._parity == PARITY_MARK:
- self._port_handle.Parity = System.IO.Ports.Parity.Mark
- elif self._parity == PARITY_SPACE:
- self._port_handle.Parity = System.IO.Ports.Parity.Space
- else:
- raise ValueError("Unsupported parity mode: %r" % self._parity)
-
- if self._stopbits == STOPBITS_ONE:
- self._port_handle.StopBits = System.IO.Ports.StopBits.One
- elif self._stopbits == STOPBITS_ONE_POINT_FIVE:
- self._port_handle.StopBits = System.IO.Ports.StopBits.OnePointFive
- elif self._stopbits == STOPBITS_TWO:
- self._port_handle.StopBits = System.IO.Ports.StopBits.Two
- else:
- raise ValueError("Unsupported number of stop bits: %r" % self._stopbits)
-
- if self._rtscts and self._xonxoff:
- self._port_handle.Handshake = System.IO.Ports.Handshake.RequestToSendXOnXOff
- elif self._rtscts:
- self._port_handle.Handshake = System.IO.Ports.Handshake.RequestToSend
- elif self._xonxoff:
- self._port_handle.Handshake = System.IO.Ports.Handshake.XOnXOff
- else:
- self._port_handle.Handshake = getattr(System.IO.Ports.Handshake, 'None') # reserved keyword in Py3k
-
- #~ def __del__(self):
- #~ self.close()
-
- def close(self):
- """Close port"""
- if self._isOpen:
- if self._port_handle:
- try:
- self._port_handle.Close()
- except System.IO.Ports.InvalidOperationException:
- # ignore errors. can happen for unplugged USB serial devices
- pass
- self._port_handle = None
- self._isOpen = False
-
- def makeDeviceName(self, port):
- try:
- return device(port)
- except TypeError, e:
- raise SerialException(str(e))
-
- # - - - - - - - - - - - - - - - - - - - - - - - -
-
- def inWaiting(self):
- """Return the number of characters currently in the input buffer."""
- if not self._port_handle: raise portNotOpenError
- return self._port_handle.BytesToRead
-
- def read(self, size=1):
- """Read size bytes from the serial port. If a timeout is set it may
- return less characters as requested. With no timeout it will block
- until the requested number of bytes is read."""
- if not self._port_handle: raise portNotOpenError
- # must use single byte reads as this is the only way to read
- # without applying encodings
- data = bytearray()
- while size:
- try:
- data.append(self._port_handle.ReadByte())
- except System.TimeoutException, e:
- break
- else:
- size -= 1
- return bytes(data)
-
- def write(self, data):
- """Output the given string over the serial port."""
- if not self._port_handle: raise portNotOpenError
- if not isinstance(data, (bytes, bytearray)):
- raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data)))
- try:
- # must call overloaded method with byte array argument
- # as this is the only one not applying encodings
- self._port_handle.Write(as_byte_array(data), 0, len(data))
- except System.TimeoutException, e:
- raise writeTimeoutError
- return len(data)
-
- def flushInput(self):
- """Clear input buffer, discarding all that is in the buffer."""
- if not self._port_handle: raise portNotOpenError
- self._port_handle.DiscardInBuffer()
-
- def flushOutput(self):
- """Clear output buffer, aborting the current output and
- discarding all that is in the buffer."""
- if not self._port_handle: raise portNotOpenError
- self._port_handle.DiscardOutBuffer()
-
- def sendBreak(self, duration=0.25):
- """Send break condition. Timed, returns to idle state after given duration."""
- if not self._port_handle: raise portNotOpenError
- import time
- self._port_handle.BreakState = True
- time.sleep(duration)
- self._port_handle.BreakState = False
-
- def setBreak(self, level=True):
- """Set break: Controls TXD. When active, to transmitting is possible."""
- if not self._port_handle: raise portNotOpenError
- self._port_handle.BreakState = bool(level)
-
- def setRTS(self, level=True):
- """Set terminal status line: Request To Send"""
- if not self._port_handle: raise portNotOpenError
- self._port_handle.RtsEnable = bool(level)
-
- def setDTR(self, level=True):
- """Set terminal status line: Data Terminal Ready"""
- if not self._port_handle: raise portNotOpenError
- self._port_handle.DtrEnable = bool(level)
-
- def getCTS(self):
- """Read terminal status line: Clear To Send"""
- if not self._port_handle: raise portNotOpenError
- return self._port_handle.CtsHolding
-
- def getDSR(self):
- """Read terminal status line: Data Set Ready"""
- if not self._port_handle: raise portNotOpenError
- return self._port_handle.DsrHolding
-
- def getRI(self):
- """Read terminal status line: Ring Indicator"""
- if not self._port_handle: raise portNotOpenError
- #~ return self._port_handle.XXX
- return False #XXX an error would be better
-
- def getCD(self):
- """Read terminal status line: Carrier Detect"""
- if not self._port_handle: raise portNotOpenError
- return self._port_handle.CDHolding
-
- # - - platform specific - - - -
- # none
-
-
-# assemble Serial class with the platform specific implementation and the base
-# for file-like behavior. for Python 2.6 and newer, that provide the new I/O
-# library, derive from io.RawIOBase
-try:
- import io
-except ImportError:
- # classic version with our own file-like emulation
- class Serial(IronSerial, FileLike):
- pass
-else:
- # io library present
- class Serial(IronSerial, io.RawIOBase):
- pass
-
-
-# Nur Testfunktion!!
-if __name__ == '__main__':
- import sys
-
- s = Serial(0)
- sys.stdio.write('%s\n' % s)
-
- s = Serial()
- sys.stdio.write('%s\n' % s)
-
-
- s.baudrate = 19200
- s.databits = 7
- s.close()
- s.port = 0
- s.open()
- sys.stdio.write('%s\n' % s)
-
diff --git a/python-serial/pyserial/build/lib/serial/serialjava.py b/python-serial/pyserial/build/lib/serial/serialjava.py
deleted file mode 100644
index 46a78f8..0000000
--- a/python-serial/pyserial/build/lib/serial/serialjava.py
+++ /dev/null
@@ -1,262 +0,0 @@
-#!jython
-#
-# Python Serial Port Extension for Win32, Linux, BSD, Jython
-# module for serial IO for Jython and JavaComm
-# see __init__.py
-#
-# (C) 2002-2008 Chris Liechti
-# this is distributed under a free software license, see license.txt
-
-from serial.serialutil import *
-
-def my_import(name):
- mod = __import__(name)
- components = name.split('.')
- for comp in components[1:]:
- mod = getattr(mod, comp)
- return mod
-
-
-def detect_java_comm(names):
- """try given list of modules and return that imports"""
- for name in names:
- try:
- mod = my_import(name)
- mod.SerialPort
- return mod
- except (ImportError, AttributeError):
- pass
- raise ImportError("No Java Communications API implementation found")
-
-
-# Java Communications API implementations
-# http://mho.republika.pl/java/comm/
-
-comm = detect_java_comm([
- 'javax.comm', # Sun/IBM
- 'gnu.io', # RXTX
-])
-
-
-def device(portnumber):
- """Turn a port number into a device name"""
- enum = comm.CommPortIdentifier.getPortIdentifiers()
- ports = []
- while enum.hasMoreElements():
- el = enum.nextElement()
- if el.getPortType() == comm.CommPortIdentifier.PORT_SERIAL:
- ports.append(el)
- return ports[portnumber].getName()
-
-
-class JavaSerial(SerialBase):
- """Serial port class, implemented with Java Communications API and
- thus usable with jython and the appropriate java extension."""
-
- def open(self):
- """Open port with current settings. This may throw a SerialException
- if the port cannot be opened."""
- if self._port is None:
- raise SerialException("Port must be configured before it can be used.")
- if self._isOpen:
- raise SerialException("Port is already open.")
- if type(self._port) == type(''): # strings are taken directly
- portId = comm.CommPortIdentifier.getPortIdentifier(self._port)
- else:
- portId = comm.CommPortIdentifier.getPortIdentifier(device(self._port)) # numbers are transformed to a comport id obj
- try:
- self.sPort = portId.open("python serial module", 10)
- except Exception, msg:
- self.sPort = None
- raise SerialException("Could not open port: %s" % msg)
- self._reconfigurePort()
- self._instream = self.sPort.getInputStream()
- self._outstream = self.sPort.getOutputStream()
- self._isOpen = True
-
- def _reconfigurePort(self):
- """Set communication parameters on opened port."""
- if not self.sPort:
- raise SerialException("Can only operate on a valid port handle")
-
- self.sPort.enableReceiveTimeout(30)
- if self._bytesize == FIVEBITS:
- jdatabits = comm.SerialPort.DATABITS_5
- elif self._bytesize == SIXBITS:
- jdatabits = comm.SerialPort.DATABITS_6
- elif self._bytesize == SEVENBITS:
- jdatabits = comm.SerialPort.DATABITS_7
- elif self._bytesize == EIGHTBITS:
- jdatabits = comm.SerialPort.DATABITS_8
- else:
- raise ValueError("unsupported bytesize: %r" % self._bytesize)
-
- if self._stopbits == STOPBITS_ONE:
- jstopbits = comm.SerialPort.STOPBITS_1
- elif stopbits == STOPBITS_ONE_POINT_FIVE:
- self._jstopbits = comm.SerialPort.STOPBITS_1_5
- elif self._stopbits == STOPBITS_TWO:
- jstopbits = comm.SerialPort.STOPBITS_2
- else:
- raise ValueError("unsupported number of stopbits: %r" % self._stopbits)
-
- if self._parity == PARITY_NONE:
- jparity = comm.SerialPort.PARITY_NONE
- elif self._parity == PARITY_EVEN:
- jparity = comm.SerialPort.PARITY_EVEN
- elif self._parity == PARITY_ODD:
- jparity = comm.SerialPort.PARITY_ODD
- elif self._parity == PARITY_MARK:
- jparity = comm.SerialPort.PARITY_MARK
- elif self._parity == PARITY_SPACE:
- jparity = comm.SerialPort.PARITY_SPACE
- else:
- raise ValueError("unsupported parity type: %r" % self._parity)
-
- jflowin = jflowout = 0
- if self._rtscts:
- jflowin |= comm.SerialPort.FLOWCONTROL_RTSCTS_IN
- jflowout |= comm.SerialPort.FLOWCONTROL_RTSCTS_OUT
- if self._xonxoff:
- jflowin |= comm.SerialPort.FLOWCONTROL_XONXOFF_IN
- jflowout |= comm.SerialPort.FLOWCONTROL_XONXOFF_OUT
-
- self.sPort.setSerialPortParams(self._baudrate, jdatabits, jstopbits, jparity)
- self.sPort.setFlowControlMode(jflowin | jflowout)
-
- if self._timeout >= 0:
- self.sPort.enableReceiveTimeout(self._timeout*1000)
- else:
- self.sPort.disableReceiveTimeout()
-
- def close(self):
- """Close port"""
- if self._isOpen:
- if self.sPort:
- self._instream.close()
- self._outstream.close()
- self.sPort.close()
- self.sPort = None
- self._isOpen = False
-
- def makeDeviceName(self, port):
- return device(port)
-
- # - - - - - - - - - - - - - - - - - - - - - - - -
-
- def inWaiting(self):
- """Return the number of characters currently in the input buffer."""
- if not self.sPort: raise portNotOpenError
- return self._instream.available()
-
- def read(self, size=1):
- """Read size bytes from the serial port. If a timeout is set it may
- return less characters as requested. With no timeout it will block
- until the requested number of bytes is read."""
- if not self.sPort: raise portNotOpenError
- read = bytearray()
- if size > 0:
- while len(read) < size:
- x = self._instream.read()
- if x == -1:
- if self.timeout >= 0:
- break
- else:
- read.append(x)
- return bytes(read)
-
- def write(self, data):
- """Output the given string over the serial port."""
- if not self.sPort: raise portNotOpenError
- if not isinstance(data, (bytes, bytearray)):
- raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data)))
- self._outstream.write(data)
- return len(data)
-
- def flushInput(self):
- """Clear input buffer, discarding all that is in the buffer."""
- if not self.sPort: raise portNotOpenError
- self._instream.skip(self._instream.available())
-
- def flushOutput(self):
- """Clear output buffer, aborting the current output and
- discarding all that is in the buffer."""
- if not self.sPort: raise portNotOpenError
- self._outstream.flush()
-
- def sendBreak(self, duration=0.25):
- """Send break condition. Timed, returns to idle state after given duration."""
- if not self.sPort: raise portNotOpenError
- self.sPort.sendBreak(duration*1000.0)
-
- def setBreak(self, level=1):
- """Set break: Controls TXD. When active, to transmitting is possible."""
- if self.fd is None: raise portNotOpenError
- raise SerialException("The setBreak function is not implemented in java.")
-
- def setRTS(self, level=1):
- """Set terminal status line: Request To Send"""
- if not self.sPort: raise portNotOpenError
- self.sPort.setRTS(level)
-
- def setDTR(self, level=1):
- """Set terminal status line: Data Terminal Ready"""
- if not self.sPort: raise portNotOpenError
- self.sPort.setDTR(level)
-
- def getCTS(self):
- """Read terminal status line: Clear To Send"""
- if not self.sPort: raise portNotOpenError
- self.sPort.isCTS()
-
- def getDSR(self):
- """Read terminal status line: Data Set Ready"""
- if not self.sPort: raise portNotOpenError
- self.sPort.isDSR()
-
- def getRI(self):
- """Read terminal status line: Ring Indicator"""
- if not self.sPort: raise portNotOpenError
- self.sPort.isRI()
-
- def getCD(self):
- """Read terminal status line: Carrier Detect"""
- if not self.sPort: raise portNotOpenError
- self.sPort.isCD()
-
-
-# assemble Serial class with the platform specific implementation and the base
-# for file-like behavior. for Python 2.6 and newer, that provide the new I/O
-# library, derive from io.RawIOBase
-try:
- import io
-except ImportError:
- # classic version with our own file-like emulation
- class Serial(JavaSerial, FileLike):
- pass
-else:
- # io library present
- class Serial(JavaSerial, io.RawIOBase):
- pass
-
-
-if __name__ == '__main__':
- s = Serial(0,
- baudrate=19200, # baudrate
- bytesize=EIGHTBITS, # number of databits
- parity=PARITY_EVEN, # enable parity checking
- stopbits=STOPBITS_ONE, # number of stopbits
- timeout=3, # set a timeout value, None for waiting forever
- xonxoff=0, # enable software flow control
- rtscts=0, # enable RTS/CTS flow control
- )
- s.setRTS(1)
- s.setDTR(1)
- s.flushInput()
- s.flushOutput()
- s.write('hello')
- sys.stdio.write('%r\n' % s.read(5))
- sys.stdio.write('%s\n' % s.inWaiting())
- del s
-
-
diff --git a/python-serial/pyserial/build/lib/serial/serialposix.py b/python-serial/pyserial/build/lib/serial/serialposix.py
deleted file mode 100644
index f225c78..0000000
--- a/python-serial/pyserial/build/lib/serial/serialposix.py
+++ /dev/null
@@ -1,651 +0,0 @@
-#!/usr/bin/env python
-#
-# Python Serial Port Extension for Win32, Linux, BSD, Jython
-# module for serial IO for POSIX compatible systems, like Linux
-# see __init__.py
-#
-# (C) 2001-2010 Chris Liechti
-# this is distributed under a free software license, see license.txt
-#
-# parts based on code from Grant B. Edwards :
-# ftp://ftp.visi.com/users/grante/python/PosixSerial.py
-#
-# references: http://www.easysw.com/~mike/serial/serial.html
-
-import sys, os, fcntl, termios, struct, select, errno, time
-from serial.serialutil import *
-
-# Do check the Python version as some constants have moved.
-if (sys.hexversion < 0x020100f0):
- import TERMIOS
-else:
- TERMIOS = termios
-
-if (sys.hexversion < 0x020200f0):
- import FCNTL
-else:
- FCNTL = fcntl
-
-# try to detect the OS so that a device can be selected...
-# this code block should supply a device() and set_special_baudrate() function
-# for the platform
-plat = sys.platform.lower()
-
-if plat[:5] == 'linux': # Linux (confirmed)
-
- def device(port):
- return '/dev/ttyS%d' % port
-
- ASYNC_SPD_MASK = 0x1030
- ASYNC_SPD_CUST = 0x0030
-
- def set_special_baudrate(port, baudrate):
- import array
- buf = array.array('i', [0] * 32)
-
- # get serial_struct
- FCNTL.ioctl(port.fd, TERMIOS.TIOCGSERIAL, buf)
-
- # set custom divisor
- buf[6] = buf[7] / baudrate
-
- # update flags
- buf[4] &= ~ASYNC_SPD_MASK
- buf[4] |= ASYNC_SPD_CUST
-
- # set serial_struct
- try:
- res = FCNTL.ioctl(port.fd, TERMIOS.TIOCSSERIAL, buf)
- except IOError:
- raise ValueError('Failed to set custom baud rate: %r' % baudrate)
-
- baudrate_constants = {
- 0: 0000000, # hang up
- 50: 0000001,
- 75: 0000002,
- 110: 0000003,
- 134: 0000004,
- 150: 0000005,
- 200: 0000006,
- 300: 0000007,
- 600: 0000010,
- 1200: 0000011,
- 1800: 0000012,
- 2400: 0000013,
- 4800: 0000014,
- 9600: 0000015,
- 19200: 0000016,
- 38400: 0000017,
- 57600: 0010001,
- 115200: 0010002,
- 230400: 0010003,
- 460800: 0010004,
- 500000: 0010005,
- 576000: 0010006,
- 921600: 0010007,
- 1000000: 0010010,
- 1152000: 0010011,
- 1500000: 0010012,
- 2000000: 0010013,
- 2500000: 0010014,
- 3000000: 0010015,
- 3500000: 0010016,
- 4000000: 0010017
- }
-
-elif plat == 'cygwin': # cygwin/win32 (confirmed)
-
- def device(port):
- return '/dev/com%d' % (port + 1)
-
- def set_special_baudrate(port, baudrate):
- raise ValueError("sorry don't know how to handle non standard baud rate on this platform")
-
- baudrate_constants = {}
-
-elif plat == 'openbsd3': # BSD (confirmed)
-
- def device(port):
- return '/dev/ttyp%d' % port
-
- def set_special_baudrate(port, baudrate):
- raise ValueError("sorry don't know how to handle non standard baud rate on this platform")
-
- baudrate_constants = {}
-
-elif plat[:3] == 'bsd' or \
- plat[:7] == 'freebsd' or \
- plat[:7] == 'openbsd': # BSD (confirmed for freebsd4: cuaa%d)
-
- def device(port):
- return '/dev/cuad%d' % port
-
- def set_special_baudrate(port, baudrate):
- raise ValueError("sorry don't know how to handle non standard baud rate on this platform")
-
- baudrate_constants = {}
-
-elif plat[:6] == 'darwin': # OS X
-
- version = os.uname()[2].split('.')
- # Tiger or above can support arbitrary serial speeds
- if int(version[0]) >= 8:
- def set_special_baudrate(port, baudrate):
- # use IOKit-specific call to set up high speeds
- import array, fcntl
- buf = array.array('i', [baudrate])
- IOSSIOSPEED = 0x80045402 #_IOW('T', 2, speed_t)
- fcntl.ioctl(port.fd, IOSSIOSPEED, buf, 1)
- else: # version < 8
- def set_special_baudrate(port, baudrate):
- raise ValueError("baud rate not supported")
-
- def device(port):
- return '/dev/cuad%d' % port
-
- baudrate_constants = {}
-
-
-elif plat[:6] == 'netbsd': # NetBSD 1.6 testing by Erk
-
- def device(port):
- return '/dev/dty%02d' % port
-
- def set_special_baudrate(port, baudrate):
- raise ValueError("sorry don't know how to handle non standard baud rate on this platform")
-
- baudrate_constants = {}
-
-elif plat[:4] == 'irix': # IRIX (partially tested)
-
- def device(port):
- return '/dev/ttyf%d' % (port+1) #XXX different device names depending on flow control
-
- def set_special_baudrate(port, baudrate):
- raise ValueError("sorry don't know how to handle non standard baud rate on this platform")
-
- baudrate_constants = {}
-
-elif plat[:2] == 'hp': # HP-UX (not tested)
-
- def device(port):
- return '/dev/tty%dp0' % (port+1)
-
- def set_special_baudrate(port, baudrate):
- raise ValueError("sorry don't know how to handle non standard baud rate on this platform")
-
- baudrate_constants = {}
-
-elif plat[:5] == 'sunos': # Solaris/SunOS (confirmed)
-
- def device(port):
- return '/dev/tty%c' % (ord('a')+port)
-
- def set_special_baudrate(port, baudrate):
- raise ValueError("sorry don't know how to handle non standard baud rate on this platform")
-
- baudrate_constants = {}
-
-elif plat[:3] == 'aix': # AIX
-
- def device(port):
- return '/dev/tty%d' % (port)
-
- def set_special_baudrate(port, baudrate):
- raise ValueError("sorry don't know how to handle non standard baud rate on this platform")
-
- baudrate_constants = {}
-
-else:
- # platform detection has failed...
- sys.stderr.write("""\
-don't know how to number ttys on this system.
-! Use an explicit path (eg /dev/ttyS1) or send this information to
-! the author of this module:
-
-sys.platform = %r
-os.name = %r
-serialposix.py version = %s
-
-also add the device name of the serial port and where the
-counting starts for the first serial port.
-e.g. 'first serial port: /dev/ttyS0'
-and with a bit luck you can get this module running...
-""" % (sys.platform, os.name, VERSION))
- # no exception, just continue with a brave attempt to build a device name
- # even if the device name is not correct for the platform it has chances
- # to work using a string with the real device name as port parameter.
- def device(portum):
- return '/dev/ttyS%d' % portnum
- def set_special_baudrate(port, baudrate):
- raise SerialException("sorry don't know how to handle non standard baud rate on this platform")
- baudrate_constants = {}
- #~ raise Exception, "this module does not run on this platform, sorry."
-
-# whats up with "aix", "beos", ....
-# they should work, just need to know the device names.
-
-
-# load some constants for later use.
-# try to use values from TERMIOS, use defaults from linux otherwise
-TIOCMGET = hasattr(TERMIOS, 'TIOCMGET') and TERMIOS.TIOCMGET or 0x5415
-TIOCMBIS = hasattr(TERMIOS, 'TIOCMBIS') and TERMIOS.TIOCMBIS or 0x5416
-TIOCMBIC = hasattr(TERMIOS, 'TIOCMBIC') and TERMIOS.TIOCMBIC or 0x5417
-TIOCMSET = hasattr(TERMIOS, 'TIOCMSET') and TERMIOS.TIOCMSET or 0x5418
-
-#TIOCM_LE = hasattr(TERMIOS, 'TIOCM_LE') and TERMIOS.TIOCM_LE or 0x001
-TIOCM_DTR = hasattr(TERMIOS, 'TIOCM_DTR') and TERMIOS.TIOCM_DTR or 0x002
-TIOCM_RTS = hasattr(TERMIOS, 'TIOCM_RTS') and TERMIOS.TIOCM_RTS or 0x004
-#TIOCM_ST = hasattr(TERMIOS, 'TIOCM_ST') and TERMIOS.TIOCM_ST or 0x008
-#TIOCM_SR = hasattr(TERMIOS, 'TIOCM_SR') and TERMIOS.TIOCM_SR or 0x010
-
-TIOCM_CTS = hasattr(TERMIOS, 'TIOCM_CTS') and TERMIOS.TIOCM_CTS or 0x020
-TIOCM_CAR = hasattr(TERMIOS, 'TIOCM_CAR') and TERMIOS.TIOCM_CAR or 0x040
-TIOCM_RNG = hasattr(TERMIOS, 'TIOCM_RNG') and TERMIOS.TIOCM_RNG or 0x080
-TIOCM_DSR = hasattr(TERMIOS, 'TIOCM_DSR') and TERMIOS.TIOCM_DSR or 0x100
-TIOCM_CD = hasattr(TERMIOS, 'TIOCM_CD') and TERMIOS.TIOCM_CD or TIOCM_CAR
-TIOCM_RI = hasattr(TERMIOS, 'TIOCM_RI') and TERMIOS.TIOCM_RI or TIOCM_RNG
-#TIOCM_OUT1 = hasattr(TERMIOS, 'TIOCM_OUT1') and TERMIOS.TIOCM_OUT1 or 0x2000
-#TIOCM_OUT2 = hasattr(TERMIOS, 'TIOCM_OUT2') and TERMIOS.TIOCM_OUT2 or 0x4000
-TIOCINQ = hasattr(TERMIOS, 'FIONREAD') and TERMIOS.FIONREAD or 0x541B
-
-TIOCM_zero_str = struct.pack('I', 0)
-TIOCM_RTS_str = struct.pack('I', TIOCM_RTS)
-TIOCM_DTR_str = struct.pack('I', TIOCM_DTR)
-
-TIOCSBRK = hasattr(TERMIOS, 'TIOCSBRK') and TERMIOS.TIOCSBRK or 0x5427
-TIOCCBRK = hasattr(TERMIOS, 'TIOCCBRK') and TERMIOS.TIOCCBRK or 0x5428
-
-
-class PosixSerial(SerialBase):
- """Serial port class POSIX implementation. Serial port configuration is
- done with termios and fcntl. Runs on Linux and many other Un*x like
- systems."""
-
- def open(self):
- """Open port with current settings. This may throw a SerialException
- if the port cannot be opened."""
- if self._port is None:
- raise SerialException("Port must be configured before it can be used.")
- if self._isOpen:
- raise SerialException("Port is already open.")
- self.fd = None
- # open
- try:
- self.fd = os.open(self.portstr, os.O_RDWR|os.O_NOCTTY|os.O_NONBLOCK)
- except Exception, msg:
- self.fd = None
- raise SerialException("could not open port %s: %s" % (self._port, msg))
- #~ fcntl.fcntl(self.fd, FCNTL.F_SETFL, 0) # set blocking
-
- try:
- self._reconfigurePort()
- except:
- try:
- os.close(self.fd)
- except:
- # ignore any exception when closing the port
- # also to keep original exception that happened when setting up
- pass
- self.fd = None
- raise
- else:
- self._isOpen = True
- #~ self.flushInput()
-
-
- def _reconfigurePort(self):
- """Set communication parameters on opened port."""
- if self.fd is None:
- raise SerialException("Can only operate on a valid file descriptor")
- custom_baud = None
-
- vmin = vtime = 0 # timeout is done via select
- if self._interCharTimeout is not None:
- vmin = 1
- vtime = int(self._interCharTimeout * 10)
- try:
- orig_attr = termios.tcgetattr(self.fd)
- iflag, oflag, cflag, lflag, ispeed, ospeed, cc = orig_attr
- except termios.error, msg: # if a port is nonexistent but has a /dev file, it'll fail here
- raise SerialException("Could not configure port: %s" % msg)
- # set up raw mode / no echo / binary
- cflag |= (TERMIOS.CLOCAL|TERMIOS.CREAD)
- lflag &= ~(TERMIOS.ICANON|TERMIOS.ECHO|TERMIOS.ECHOE|TERMIOS.ECHOK|TERMIOS.ECHONL|
- TERMIOS.ISIG|TERMIOS.IEXTEN) #|TERMIOS.ECHOPRT
- for flag in ('ECHOCTL', 'ECHOKE'): # netbsd workaround for Erk
- if hasattr(TERMIOS, flag):
- lflag &= ~getattr(TERMIOS, flag)
-
- oflag &= ~(TERMIOS.OPOST)
- iflag &= ~(TERMIOS.INLCR|TERMIOS.IGNCR|TERMIOS.ICRNL|TERMIOS.IGNBRK)
- if hasattr(TERMIOS, 'IUCLC'):
- iflag &= ~TERMIOS.IUCLC
- if hasattr(TERMIOS, 'PARMRK'):
- iflag &= ~TERMIOS.PARMRK
-
- # setup baud rate
- try:
- ispeed = ospeed = getattr(TERMIOS, 'B%s' % (self._baudrate))
- except AttributeError:
- try:
- ispeed = ospeed = baudrate_constants[self._baudrate]
- except KeyError:
- #~ raise ValueError('Invalid baud rate: %r' % self._baudrate)
- # may need custom baud rate, it isn't in our list.
- ispeed = ospeed = getattr(TERMIOS, 'B38400')
- try:
- custom_baud = int(self._baudrate) # store for later
- except ValueError:
- raise ValueError('Invalid baud rate: %r' % self._baudrate)
- else:
- if custom_baud < 0:
- raise ValueError('Invalid baud rate: %r' % self._baudrate)
-
- # setup char len
- cflag &= ~TERMIOS.CSIZE
- if self._bytesize == 8:
- cflag |= TERMIOS.CS8
- elif self._bytesize == 7:
- cflag |= TERMIOS.CS7
- elif self._bytesize == 6:
- cflag |= TERMIOS.CS6
- elif self._bytesize == 5:
- cflag |= TERMIOS.CS5
- else:
- raise ValueError('Invalid char len: %r' % self._bytesize)
- # setup stopbits
- if self._stopbits == STOPBITS_ONE:
- cflag &= ~(TERMIOS.CSTOPB)
- elif self._stopbits == STOPBITS_ONE_POINT_FIVE:
- cflag |= (TERMIOS.CSTOPB) # XXX same as TWO.. there is no POSIX support for 1.5
- elif self._stopbits == STOPBITS_TWO:
- cflag |= (TERMIOS.CSTOPB)
- else:
- raise ValueError('Invalid stop bit specification: %r' % self._stopbits)
- # setup parity
- iflag &= ~(TERMIOS.INPCK|TERMIOS.ISTRIP)
- if self._parity == PARITY_NONE:
- cflag &= ~(TERMIOS.PARENB|TERMIOS.PARODD)
- elif self._parity == PARITY_EVEN:
- cflag &= ~(TERMIOS.PARODD)
- cflag |= (TERMIOS.PARENB)
- elif self._parity == PARITY_ODD:
- cflag |= (TERMIOS.PARENB|TERMIOS.PARODD)
- else:
- raise ValueError('Invalid parity: %r' % self._parity)
- # setup flow control
- # xonxoff
- if hasattr(TERMIOS, 'IXANY'):
- if self._xonxoff:
- iflag |= (TERMIOS.IXON|TERMIOS.IXOFF) #|TERMIOS.IXANY)
- else:
- iflag &= ~(TERMIOS.IXON|TERMIOS.IXOFF|TERMIOS.IXANY)
- else:
- if self._xonxoff:
- iflag |= (TERMIOS.IXON|TERMIOS.IXOFF)
- else:
- iflag &= ~(TERMIOS.IXON|TERMIOS.IXOFF)
- # rtscts
- if hasattr(TERMIOS, 'CRTSCTS'):
- if self._rtscts:
- cflag |= (TERMIOS.CRTSCTS)
- else:
- cflag &= ~(TERMIOS.CRTSCTS)
- elif hasattr(TERMIOS, 'CNEW_RTSCTS'): # try it with alternate constant name
- if self._rtscts:
- cflag |= (TERMIOS.CNEW_RTSCTS)
- else:
- cflag &= ~(TERMIOS.CNEW_RTSCTS)
- # XXX should there be a warning if setting up rtscts (and xonxoff etc) fails??
-
- # buffer
- # vmin "minimal number of characters to be read. = for non blocking"
- if vmin < 0 or vmin > 255:
- raise ValueError('Invalid vmin: %r ' % vmin)
- cc[TERMIOS.VMIN] = vmin
- # vtime
- if vtime < 0 or vtime > 255:
- raise ValueError('Invalid vtime: %r' % vtime)
- cc[TERMIOS.VTIME] = vtime
- # activate settings
- if [iflag, oflag, cflag, lflag, ispeed, ospeed, cc] != orig_attr:
- termios.tcsetattr(self.fd, TERMIOS.TCSANOW, [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
-
- # apply custom baud rate, if any
- if custom_baud is not None:
- set_special_baudrate(self, custom_baud)
-
- def close(self):
- """Close port"""
- if self._isOpen:
- if self.fd is not None:
- os.close(self.fd)
- self.fd = None
- self._isOpen = False
-
- def makeDeviceName(self, port):
- return device(port)
-
- # - - - - - - - - - - - - - - - - - - - - - - - -
-
- def inWaiting(self):
- """Return the number of characters currently in the input buffer."""
- #~ s = fcntl.ioctl(self.fd, TERMIOS.FIONREAD, TIOCM_zero_str)
- s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str)
- return struct.unpack('I',s)[0]
-
- # select based implementation, proved to work on many systems
- def read(self, size=1):
- """Read size bytes from the serial port. If a timeout is set it may
- return less characters as requested. With no timeout it will block
- until the requested number of bytes is read."""
- if not self._isOpen: raise portNotOpenError
- read = bytearray()
- while len(read) < size:
- ready,_,_ = select.select([self.fd],[],[], self._timeout)
- # If select was used with a timeout, and the timeout occurs, it
- # returns with empty lists -> thus abort read operation.
- # For timeout == 0 (non-blocking operation) also abort when there
- # is nothing to read.
- if not ready:
- break # timeout
- buf = os.read(self.fd, size-len(read))
- # read should always return some data as select reported it was
- # ready to read when we get to this point.
- if not buf:
- # Disconnected devices, at least on Linux, show the
- # behavior that they are always ready to read immediately
- # but reading returns nothing.
- raise SerialException('device reports readiness to read but returned no data (device disconnected?)')
- read.extend(buf)
- return bytes(read)
-
- def write(self, data):
- """Output the given string over the serial port."""
- if not self._isOpen: raise portNotOpenError
- t = len(data)
- d = data
- if self._writeTimeout is not None and self._writeTimeout > 0:
- timeout = time.time() + self._writeTimeout
- else:
- timeout = None
- while t > 0:
- try:
- n = os.write(self.fd, d)
- if timeout:
- # when timeout is set, use select to wait for being ready
- # with the time left as timeout
- timeleft = timeout - time.time()
- if timeleft < 0:
- raise writeTimeoutError
- _, ready, _ = select.select([], [self.fd], [], timeleft)
- if not ready:
- raise writeTimeoutError
- d = d[n:]
- t = t - n
- except OSError, v:
- if v.errno != errno.EAGAIN:
- raise SerialException('write failed: %s' % (v,))
- return len(data)
-
- def flush(self):
- """Flush of file like objects. In this case, wait until all data
- is written."""
- self.drainOutput()
-
- def flushInput(self):
- """Clear input buffer, discarding all that is in the buffer."""
- if not self._isOpen: raise portNotOpenError
- termios.tcflush(self.fd, TERMIOS.TCIFLUSH)
-
- def flushOutput(self):
- """Clear output buffer, aborting the current output and
- discarding all that is in the buffer."""
- if not self._isOpen: raise portNotOpenError
- termios.tcflush(self.fd, TERMIOS.TCOFLUSH)
-
- def sendBreak(self, duration=0.25):
- """Send break condition. Timed, returns to idle state after given duration."""
- if not self._isOpen: raise portNotOpenError
- termios.tcsendbreak(self.fd, int(duration/0.25))
-
- def setBreak(self, level=1):
- """Set break: Controls TXD. When active, no transmitting is possible."""
- if self.fd is None: raise portNotOpenError
- if level:
- fcntl.ioctl(self.fd, TIOCSBRK)
- else:
- fcntl.ioctl(self.fd, TIOCCBRK)
-
- def setRTS(self, level=1):
- """Set terminal status line: Request To Send"""
- if not self._isOpen: raise portNotOpenError
- if level:
- fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_RTS_str)
- else:
- fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_RTS_str)
-
- def setDTR(self, level=1):
- """Set terminal status line: Data Terminal Ready"""
- if not self._isOpen: raise portNotOpenError
- if level:
- fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_DTR_str)
- else:
- fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_DTR_str)
-
- def getCTS(self):
- """Read terminal status line: Clear To Send"""
- if not self._isOpen: raise portNotOpenError
- s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
- return struct.unpack('I',s)[0] & TIOCM_CTS != 0
-
- def getDSR(self):
- """Read terminal status line: Data Set Ready"""
- if not self._isOpen: raise portNotOpenError
- s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
- return struct.unpack('I',s)[0] & TIOCM_DSR != 0
-
- def getRI(self):
- """Read terminal status line: Ring Indicator"""
- if not self._isOpen: raise portNotOpenError
- s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
- return struct.unpack('I',s)[0] & TIOCM_RI != 0
-
- def getCD(self):
- """Read terminal status line: Carrier Detect"""
- if not self._isOpen: raise portNotOpenError
- s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
- return struct.unpack('I',s)[0] & TIOCM_CD != 0
-
- # - - platform specific - - - -
-
- def drainOutput(self):
- """internal - not portable!"""
- if not self._isOpen: raise portNotOpenError
- termios.tcdrain(self.fd)
-
- def nonblocking(self):
- """internal - not portable!"""
- if not self._isOpen: raise portNotOpenError
- fcntl.fcntl(self.fd, FCNTL.F_SETFL, os.O_NONBLOCK)
-
- def fileno(self):
- """For easier use of the serial port instance with select.
- WARNING: this function is not portable to different platforms!"""
- if not self._isOpen: raise portNotOpenError
- return self.fd
-
- def flowControl(self, enable):
- """manually control flow - when hardware or software flow control is
- enabled"""
- if not self._isOpen: raise portNotOpenError
- if enable:
- termios.tcflow(self.fd, TERMIOS.TCION)
- else:
- termios.tcflow(self.fd, TERMIOS.TCIOFF)
-
-
-# assemble Serial class with the platform specifc implementation and the base
-# for file-like behavior. for Python 2.6 and newer, that provide the new I/O
-# library, derrive from io.RawIOBase
-try:
- import io
-except ImportError:
- # classic version with our own file-like emulation
- class Serial(PosixSerial, FileLike):
- pass
-else:
- # io library present
- class Serial(PosixSerial, io.RawIOBase):
- pass
-
-class PosixPollSerial(Serial):
- """poll based read implementation. not all systems support poll properly.
- however this one has better handling of errors, such as a device
- disconnecting while it's in use (e.g. USB-serial unplugged)"""
-
- def read(self, size=1):
- """Read size bytes from the serial port. If a timeout is set it may
- return less characters as requested. With no timeout it will block
- until the requested number of bytes is read."""
- if self.fd is None: raise portNotOpenError
- read = bytearray()
- poll = select.poll()
- poll.register(self.fd, select.POLLIN|select.POLLERR|select.POLLHUP|select.POLLNVAL)
- if size > 0:
- while len(read) < size:
- # print "\tread(): size",size, "have", len(read) #debug
- # wait until device becomes ready to read (or something fails)
- for fd, event in poll.poll(self._timeout*1000):
- if event & (select.POLLERR|select.POLLHUP|select.POLLNVAL):
- raise SerialException('device reports error (poll)')
- # we don't care if it is select.POLLIN or timeout, that's
- # handled below
- buf = os.read(self.fd, size - len(read))
- read.extend(buf)
- if ((self._timeout is not None and self._timeout >= 0) or
- (self._interCharTimeout is not None and self._interCharTimeout > 0)) and not buf:
- break # early abort on timeout
- return bytes(read)
-
-
-if __name__ == '__main__':
- s = Serial(0,
- baudrate=19200, # baud rate
- bytesize=EIGHTBITS, # number of data bits
- parity=PARITY_EVEN, # enable parity checking
- stopbits=STOPBITS_ONE, # number of stop bits
- timeout=3, # set a timeout value, None for waiting forever
- xonxoff=0, # enable software flow control
- rtscts=0, # enable RTS/CTS flow control
- )
- s.setRTS(1)
- s.setDTR(1)
- s.flushInput()
- s.flushOutput()
- s.write('hello')
- sys.stdout.write('%r\n' % s.read(5))
- sys.stdout.write('%s\n' % s.inWaiting())
- del s
-
diff --git a/python-serial/pyserial/build/lib/serial/serialutil.py b/python-serial/pyserial/build/lib/serial/serialutil.py
deleted file mode 100644
index c372280..0000000
--- a/python-serial/pyserial/build/lib/serial/serialutil.py
+++ /dev/null
@@ -1,527 +0,0 @@
-#! python
-# Python Serial Port Extension for Win32, Linux, BSD, Jython
-# see __init__.py
-#
-# (C) 2001-2010 Chris Liechti
-# this is distributed under a free software license, see license.txt
-
-# compatibility for older Python < 2.6
-try:
- bytes
- bytearray
-except (NameError, AttributeError):
- # Python older than 2.6 do not have these types. Like for Python 2.6 they
- # should behave like str. For Python older than 3.0 we want to work with
- # strings anyway, only later versions have a true bytes type.
- bytes = str
- # bytearray is a mutable type that is easily turned into an instance of
- # bytes
- class bytearray(list):
- # for bytes(bytearray()) usage
- def __str__(self): return ''.join(self)
- def __repr__(self): return 'bytearray(%r)' % ''.join(self)
- # append automatically converts integers to characters
- def append(self, item):
- if isinstance(item, str):
- list.append(self, item)
- else:
- list.append(self, chr(item))
- # +=
- def __iadd__(self, other):
- for byte in other:
- self.append(byte)
- return self
-
- def __getslice__(self, i, j):
- return bytearray(list.__getslice__(self, i, j))
-
- def __getitem__(self, item):
- if isinstance(item, slice):
- return bytearray(list.__getitem__(self, item))
- else:
- return ord(list.__getitem__(self, item))
-
- def __eq__(self, other):
- if isinstance(other, basestring):
- other = bytearray(other)
- return list.__eq__(self, other)
-
-# all Python versions prior 3.x convert str([17]) to '[17]' instead of '\x11'
-# so a simple bytes(sequence) doesn't work for all versions
-def to_bytes(seq):
- """convert a sequence to a bytes type"""
- b = bytearray()
- for item in seq:
- b.append(item) # this one handles int and str
- return bytes(b)
-
-# create control bytes
-XON = to_bytes([17])
-XOFF = to_bytes([19])
-
-CR = to_bytes([13])
-LF = to_bytes([10])
-
-
-PARITY_NONE, PARITY_EVEN, PARITY_ODD, PARITY_MARK, PARITY_SPACE = 'N', 'E', 'O', 'M', 'S'
-STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO = (1, 1.5, 2)
-FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS = (5, 6, 7, 8)
-
-PARITY_NAMES = {
- PARITY_NONE: 'None',
- PARITY_EVEN: 'Even',
- PARITY_ODD: 'Odd',
- PARITY_MARK: 'Mark',
- PARITY_SPACE: 'Space',
-}
-
-
-class SerialException(IOError):
- """Base class for serial port related exceptions."""
-
-
-class SerialTimeoutException(SerialException):
- """Write timeouts give an exception"""
-
-
-writeTimeoutError = SerialTimeoutException("Write timeout")
-portNotOpenError = ValueError('Attempting to use a port that is not open')
-
-
-class FileLike(object):
- """An abstract file like class.
-
- This class implements readline and readlines based on read and
- writelines based on write.
- This class is used to provide the above functions for to Serial
- port objects.
-
- Note that when the serial port was opened with _NO_ timeout that
- readline blocks until it sees a newline (or the specified size is
- reached) and that readlines would never return and therefore
- refuses to work (it raises an exception in this case)!
- """
-
- def __init__(self):
- self.closed = True
-
- def close(self):
- self.closed = True
-
- # so that ports are closed when objects are discarded
- def __del__(self):
- """Destructor. Calls close()."""
- # The try/except block is in case this is called at program
- # exit time, when it's possible that globals have already been
- # deleted, and then the close() call might fail. Since
- # there's nothing we can do about such failures and they annoy
- # the end users, we suppress the traceback.
- try:
- self.close()
- except:
- pass
-
- def writelines(self, sequence):
- for line in sequence:
- self.write(line)
-
- def flush(self):
- """flush of file like objects"""
- pass
-
- # iterator for e.g. "for line in Serial(0): ..." usage
- def next(self):
- line = self.readline()
- if not line: raise StopIteration
- return line
-
- def __iter__(self):
- return self
-
- def readline(self, size=None, eol=LF):
- """read a line which is terminated with end-of-line (eol) character
- ('\n' by default) or until timeout."""
- leneol = len(eol)
- line = bytearray()
- while True:
- c = self.read(1)
- if c:
- line += c
- if line[-leneol:] == eol:
- break
- if size is not None and len(line) >= size:
- break
- else:
- break
- return bytes(line)
-
- def readlines(self, sizehint=None, eol=LF):
- """read a list of lines, until timeout.
- sizehint is ignored."""
- if self.timeout is None:
- raise ValueError("Serial port MUST have enabled timeout for this function!")
- leneol = len(eol)
- lines = []
- while True:
- line = self.readline(eol=eol)
- if line:
- lines.append(line)
- if line[-leneol:] != eol: # was the line received with a timeout?
- break
- else:
- break
- return lines
-
- def xreadlines(self, sizehint=None):
- """Read lines, implemented as generator. It will raise StopIteration on
- timeout (empty read). sizehint is ignored."""
- while True:
- line = self.readline()
- if not line: break
- yield line
-
- # other functions of file-likes - not used by pySerial
-
- #~ readinto(b)
-
- def seek(self, pos, whence=0):
- raise IOError("file is not seekable")
-
- def tell(self):
- raise IOError("file is not seekable")
-
- def truncate(self, n=None):
- raise IOError("file is not seekable")
-
- def isatty(self):
- return False
-
-
-class SerialBase(object):
- """Serial port base class. Provides __init__ function and properties to
- get/set port settings."""
-
- # default values, may be overridden in subclasses that do not support all values
- BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
- 9600, 19200, 38400, 57600, 115200, 230400, 460800, 500000,
- 576000, 921600, 1000000, 1152000, 1500000, 2000000, 2500000,
- 3000000, 3500000, 4000000)
- BYTESIZES = (FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS)
- PARITIES = (PARITY_NONE, PARITY_EVEN, PARITY_ODD, PARITY_MARK, PARITY_SPACE)
- STOPBITS = (STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO)
-
- def __init__(self,
- port = None, # number of device, numbering starts at
- # zero. if everything fails, the user
- # can specify a device string, note
- # that this isn't portable anymore
- # port will be opened if one is specified
- baudrate=9600, # baud rate
- bytesize=EIGHTBITS, # number of data bits
- parity=PARITY_NONE, # enable parity checking
- stopbits=STOPBITS_ONE, # number of stop bits
- timeout=None, # set a timeout value, None to wait forever
- xonxoff=False, # enable software flow control
- rtscts=False, # enable RTS/CTS flow control
- writeTimeout=None, # set a timeout for writes
- dsrdtr=False, # None: use rtscts setting, dsrdtr override if True or False
- interCharTimeout=None # Inter-character timeout, None to disable
- ):
- """Initialize comm port object. If a port is given, then the port will be
- opened immediately. Otherwise a Serial port object in closed state
- is returned."""
-
- self._isOpen = False
- self._port = None # correct value is assigned below through properties
- self._baudrate = None # correct value is assigned below through properties
- self._bytesize = None # correct value is assigned below through properties
- self._parity = None # correct value is assigned below through properties
- self._stopbits = None # correct value is assigned below through properties
- self._timeout = None # correct value is assigned below through properties
- self._writeTimeout = None # correct value is assigned below through properties
- self._xonxoff = None # correct value is assigned below through properties
- self._rtscts = None # correct value is assigned below through properties
- self._dsrdtr = None # correct value is assigned below through properties
- self._interCharTimeout = None # correct value is assigned below through properties
-
- # assign values using get/set methods using the properties feature
- self.port = port
- self.baudrate = baudrate
- self.bytesize = bytesize
- self.parity = parity
- self.stopbits = stopbits
- self.timeout = timeout
- self.writeTimeout = writeTimeout
- self.xonxoff = xonxoff
- self.rtscts = rtscts
- self.dsrdtr = dsrdtr
- self.interCharTimeout = interCharTimeout
-
- if port is not None:
- self.open()
-
- def isOpen(self):
- """Check if the port is opened."""
- return self._isOpen
-
- # - - - - - - - - - - - - - - - - - - - - - - - -
-
- # TODO: these are not really needed as the is the BAUDRATES etc. attribute...
- # maybe i remove them before the final release...
-
- def getSupportedBaudrates(self):
- return [(str(b), b) for b in self.BAUDRATES]
-
- def getSupportedByteSizes(self):
- return [(str(b), b) for b in self.BYTESIZES]
-
- def getSupportedStopbits(self):
- return [(str(b), b) for b in self.STOPBITS]
-
- def getSupportedParities(self):
- return [(PARITY_NAMES[b], b) for b in self.PARITIES]
-
- # - - - - - - - - - - - - - - - - - - - - - - - -
-
- def setPort(self, port):
- """Change the port. The attribute portstr is set to a string that
- contains the name of the port."""
-
- was_open = self._isOpen
- if was_open: self.close()
- if port is not None:
- if isinstance(port, basestring):
- self.portstr = port
- else:
- self.portstr = self.makeDeviceName(port)
- else:
- self.portstr = None
- self._port = port
- self.name = self.portstr
- if was_open: self.open()
-
- def getPort(self):
- """Get the current port setting. The value that was passed on init or using
- setPort() is passed back. See also the attribute portstr which contains
- the name of the port as a string."""
- return self._port
-
- port = property(getPort, setPort, doc="Port setting")
-
-
- def setBaudrate(self, baudrate):
- """Change baud rate. It raises a ValueError if the port is open and the
- baud rate is not possible. If the port is closed, then the value is
- accepted and the exception is raised when the port is opened."""
- try:
- self._baudrate = int(baudrate)
- except TypeError:
- raise ValueError("Not a valid baudrate: %r" % (baudrate,))
- else:
- if self._isOpen: self._reconfigurePort()
-
- def getBaudrate(self):
- """Get the current baud rate setting."""
- return self._baudrate
-
- baudrate = property(getBaudrate, setBaudrate, doc="Baud rate setting")
-
-
- def setByteSize(self, bytesize):
- """Change byte size."""
- if bytesize not in self.BYTESIZES: raise ValueError("Not a valid byte size: %r" % (bytesize,))
- self._bytesize = bytesize
- if self._isOpen: self._reconfigurePort()
-
- def getByteSize(self):
- """Get the current byte size setting."""
- return self._bytesize
-
- bytesize = property(getByteSize, setByteSize, doc="Byte size setting")
-
-
- def setParity(self, parity):
- """Change parity setting."""
- if parity not in self.PARITIES: raise ValueError("Not a valid parity: %r" % (parity,))
- self._parity = parity
- if self._isOpen: self._reconfigurePort()
-
- def getParity(self):
- """Get the current parity setting."""
- return self._parity
-
- parity = property(getParity, setParity, doc="Parity setting")
-
-
- def setStopbits(self, stopbits):
- """Change stop bits size."""
- if stopbits not in self.STOPBITS: raise ValueError("Not a valid stop bit size: %r" % (stopbits,))
- self._stopbits = stopbits
- if self._isOpen: self._reconfigurePort()
-
- def getStopbits(self):
- """Get the current stop bits setting."""
- return self._stopbits
-
- stopbits = property(getStopbits, setStopbits, doc="Stop bits setting")
-
-
- def setTimeout(self, timeout):
- """Change timeout setting."""
- if timeout is not None:
- try:
- timeout + 1 # test if it's a number, will throw a TypeError if not...
- except TypeError:
- raise ValueError("Not a valid timeout: %r" % (timeout,))
- if timeout < 0: raise ValueError("Not a valid timeout: %r" % (timeout,))
- self._timeout = timeout
- if self._isOpen: self._reconfigurePort()
-
- def getTimeout(self):
- """Get the current timeout setting."""
- return self._timeout
-
- timeout = property(getTimeout, setTimeout, doc="Timeout setting for read()")
-
-
- def setWriteTimeout(self, timeout):
- """Change timeout setting."""
- if timeout is not None:
- if timeout < 0: raise ValueError("Not a valid timeout: %r" % (timeout,))
- try:
- timeout + 1 #test if it's a number, will throw a TypeError if not...
- except TypeError:
- raise ValueError("Not a valid timeout: %r" % timeout)
-
- self._writeTimeout = timeout
- if self._isOpen: self._reconfigurePort()
-
- def getWriteTimeout(self):
- """Get the current timeout setting."""
- return self._writeTimeout
-
- writeTimeout = property(getWriteTimeout, setWriteTimeout, doc="Timeout setting for write()")
-
-
- def setXonXoff(self, xonxoff):
- """Change XON/XOFF setting."""
- self._xonxoff = xonxoff
- if self._isOpen: self._reconfigurePort()
-
- def getXonXoff(self):
- """Get the current XON/XOFF setting."""
- return self._xonxoff
-
- xonxoff = property(getXonXoff, setXonXoff, doc="XON/XOFF setting")
-
- def setRtsCts(self, rtscts):
- """Change RTS/CTS flow control setting."""
- self._rtscts = rtscts
- if self._isOpen: self._reconfigurePort()
-
- def getRtsCts(self):
- """Get the current RTS/CTS flow control setting."""
- return self._rtscts
-
- rtscts = property(getRtsCts, setRtsCts, doc="RTS/CTS flow control setting")
-
- def setDsrDtr(self, dsrdtr=None):
- """Change DsrDtr flow control setting."""
- if dsrdtr is None:
- # if not set, keep backwards compatibility and follow rtscts setting
- self._dsrdtr = self._rtscts
- else:
- # if defined independently, follow its value
- self._dsrdtr = dsrdtr
- if self._isOpen: self._reconfigurePort()
-
- def getDsrDtr(self):
- """Get the current DSR/DTR flow control setting."""
- return self._dsrdtr
-
- dsrdtr = property(getDsrDtr, setDsrDtr, "DSR/DTR flow control setting")
-
- def setInterCharTimeout(self, interCharTimeout):
- """Change inter-character timeout setting."""
- if interCharTimeout is not None:
- if interCharTimeout < 0: raise ValueError("Not a valid timeout: %r" % interCharTimeout)
- try:
- interCharTimeout + 1 # test if it's a number, will throw a TypeError if not...
- except TypeError:
- raise ValueError("Not a valid timeout: %r" % interCharTimeout)
-
- self._interCharTimeout = interCharTimeout
- if self._isOpen: self._reconfigurePort()
-
- def getInterCharTimeout(self):
- """Get the current inter-character timeout setting."""
- return self._interCharTimeout
-
- interCharTimeout = property(getInterCharTimeout, setInterCharTimeout, doc="Inter-character timeout setting for read()")
-
- # - - - - - - - - - - - - - - - - - - - - - - - -
-
- _SETTINGS = ('baudrate', 'bytesize', 'parity', 'stopbits', 'xonxoff',
- 'dsrdtr', 'rtscts', 'timeout', 'writeTimeout', 'interCharTimeout')
-
- def getSettingsDict(self):
- """Get current port settings as a dictionary. For use with
- applySettingsDict"""
- return dict([(key, getattr(self, '_'+key)) for key in self._SETTINGS])
-
- def applySettingsDict(self, d):
- """apply stored settings from a dictionary returned from
- getSettingsDict. it's allowed to delete keys from the dictionary. these
- values will simply left unchanged."""
- for key in self._SETTINGS:
- if d[key] != getattr(self, '_'+key): # check against internal "_" value
- setattr(self, key, d[key]) # set non "_" value to use properties write function
-
- # - - - - - - - - - - - - - - - - - - - - - - - -
-
- def __repr__(self):
- """String representation of the current port settings and its state."""
- return "%s(port=%r, baudrate=%r, bytesize=%r, parity=%r, stopbits=%r, timeout=%r, xonxoff=%r, rtscts=%r, dsrdtr=%r)" % (
- self.__class__.__name__,
- id(self),
- self._isOpen,
- self.portstr,
- self.baudrate,
- self.bytesize,
- self.parity,
- self.stopbits,
- self.timeout,
- self.xonxoff,
- self.rtscts,
- self.dsrdtr,
- )
-
-
- # - - - - - - - - - - - - - - - - - - - - - - - -
- # compatibility with io library
-
- def readable(self): return True
- def writable(self): return True
- def seekable(self): return False
- def readinto(self, b):
- data = self.read(len(b))
- n = len(data)
- try:
- b[:n] = data
- except TypeError, err:
- import array
- if not isinstance(b, array.array):
- raise err
- b[:n] = array.array('b', data)
- return n
-
-
-if __name__ == '__main__':
- import sys
- s = SerialBase()
- sys.stdout.write('port name: %s\n' % s.portstr)
- sys.stdout.write('baud rates: %s\n' % s.getSupportedBaudrates())
- sys.stdout.write('byte sizes: %s\n' % s.getSupportedByteSizes())
- sys.stdout.write('parities: %s\n' % s.getSupportedParities())
- sys.stdout.write('stop bits: %s\n' % s.getSupportedStopbits())
- sys.stdout.write('%s\n' % s)
diff --git a/python-serial/pyserial/build/lib/serial/serialwin32.py b/python-serial/pyserial/build/lib/serial/serialwin32.py
deleted file mode 100644
index 4c7f23d..0000000
--- a/python-serial/pyserial/build/lib/serial/serialwin32.py
+++ /dev/null
@@ -1,408 +0,0 @@
-#! python
-# Python Serial Port Extension for Win32, Linux, BSD, Jython
-# serial driver for win32
-# see __init__.py
-#
-# (C) 2001-2011 Chris Liechti
-# this is distributed under a free software license, see license.txt
-#
-# Initial patch to use ctypes by Giovanni Bajo
-
-import ctypes
-from serial import win32
-
-from serial.serialutil import *
-
-
-def device(portnum):
- """Turn a port number into a device name"""
- return 'COM%d' % (portnum+1) # numbers are transformed to a string
-
-
-class Win32Serial(SerialBase):
- """Serial port implementation for Win32 based on ctypes."""
-
- BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
- 9600, 19200, 38400, 57600, 115200)
-
- def __init__(self, *args, **kwargs):
- self.hComPort = None
- self._rtsToggle = False
- SerialBase.__init__(self, *args, **kwargs)
-
- def open(self):
- """Open port with current settings. This may throw a SerialException
- if the port cannot be opened."""
- if self._port is None:
- raise SerialException("Port must be configured before it can be used.")
- if self._isOpen:
- raise SerialException("Port is already open.")
- # the "\\.\COMx" format is required for devices other than COM1-COM8
- # not all versions of windows seem to support this properly
- # so that the first few ports are used with the DOS device name
- port = self.portstr
- try:
- if port.upper().startswith('COM') and int(port[3:]) > 8:
- port = '\\\\.\\' + port
- except ValueError:
- # for like COMnotanumber
- pass
- self.hComPort = win32.CreateFile(port,
- win32.GENERIC_READ | win32.GENERIC_WRITE,
- 0, # exclusive access
- None, # no security
- win32.OPEN_EXISTING,
- win32.FILE_ATTRIBUTE_NORMAL | win32.FILE_FLAG_OVERLAPPED,
- 0)
- if self.hComPort == win32.INVALID_HANDLE_VALUE:
- self.hComPort = None # 'cause __del__ is called anyway
- raise SerialException("could not open port %s: %s" % (self.portstr, ctypes.WinError()))
-
- # Setup a 4k buffer
- win32.SetupComm(self.hComPort, 4096, 4096)
-
- # Save original timeout values:
- self._orgTimeouts = win32.COMMTIMEOUTS()
- win32.GetCommTimeouts(self.hComPort, ctypes.byref(self._orgTimeouts))
-
- self._rtsState = win32.RTS_CONTROL_ENABLE
- self._dtrState = win32.DTR_CONTROL_ENABLE
-
- self._reconfigurePort()
-
- # Clear buffers:
- # Remove anything that was there
- win32.PurgeComm(self.hComPort,
- win32.PURGE_TXCLEAR | win32.PURGE_TXABORT |
- win32.PURGE_RXCLEAR | win32.PURGE_RXABORT)
-
- self._overlappedRead = win32.OVERLAPPED()
- self._overlappedRead.hEvent = win32.CreateEvent(None, 1, 0, None)
- self._overlappedWrite = win32.OVERLAPPED()
- #~ self._overlappedWrite.hEvent = win32.CreateEvent(None, 1, 0, None)
- self._overlappedWrite.hEvent = win32.CreateEvent(None, 0, 0, None)
- self._isOpen = True
-
- def _reconfigurePort(self):
- """Set communication parameters on opened port."""
- if not self.hComPort:
- raise SerialException("Can only operate on a valid port handle")
-
- # Set Windows timeout values
- # timeouts is a tuple with the following items:
- # (ReadIntervalTimeout,ReadTotalTimeoutMultiplier,
- # ReadTotalTimeoutConstant,WriteTotalTimeoutMultiplier,
- # WriteTotalTimeoutConstant)
- if self._timeout is None:
- timeouts = (0, 0, 0, 0, 0)
- elif self._timeout == 0:
- timeouts = (win32.MAXDWORD, 0, 0, 0, 0)
- else:
- timeouts = (0, 0, int(self._timeout*1000), 0, 0)
- if self._timeout != 0 and self._interCharTimeout is not None:
- timeouts = (int(self._interCharTimeout * 1000),) + timeouts[1:]
-
- if self._writeTimeout is None:
- pass
- elif self._writeTimeout == 0:
- timeouts = timeouts[:-2] + (0, win32.MAXDWORD)
- else:
- timeouts = timeouts[:-2] + (0, int(self._writeTimeout*1000))
- win32.SetCommTimeouts(self.hComPort, ctypes.byref(win32.COMMTIMEOUTS(*timeouts)))
-
- win32.SetCommMask(self.hComPort, win32.EV_ERR)
-
- # Setup the connection info.
- # Get state and modify it:
- comDCB = win32.DCB()
- win32.GetCommState(self.hComPort, ctypes.byref(comDCB))
- comDCB.BaudRate = self._baudrate
-
- if self._bytesize == FIVEBITS:
- comDCB.ByteSize = 5
- elif self._bytesize == SIXBITS:
- comDCB.ByteSize = 6
- elif self._bytesize == SEVENBITS:
- comDCB.ByteSize = 7
- elif self._bytesize == EIGHTBITS:
- comDCB.ByteSize = 8
- else:
- raise ValueError("Unsupported number of data bits: %r" % self._bytesize)
-
- if self._parity == PARITY_NONE:
- comDCB.Parity = win32.NOPARITY
- comDCB.fParity = 0 # Disable Parity Check
- elif self._parity == PARITY_EVEN:
- comDCB.Parity = win32.EVENPARITY
- comDCB.fParity = 1 # Enable Parity Check
- elif self._parity == PARITY_ODD:
- comDCB.Parity = win32.ODDPARITY
- comDCB.fParity = 1 # Enable Parity Check
- elif self._parity == PARITY_MARK:
- comDCB.Parity = win32.MARKPARITY
- comDCB.fParity = 1 # Enable Parity Check
- elif self._parity == PARITY_SPACE:
- comDCB.Parity = win32.SPACEPARITY
- comDCB.fParity = 1 # Enable Parity Check
- else:
- raise ValueError("Unsupported parity mode: %r" % self._parity)
-
- if self._stopbits == STOPBITS_ONE:
- comDCB.StopBits = win32.ONESTOPBIT
- elif self._stopbits == STOPBITS_ONE_POINT_FIVE:
- comDCB.StopBits = win32.ONE5STOPBITS
- elif self._stopbits == STOPBITS_TWO:
- comDCB.StopBits = win32.TWOSTOPBITS
- else:
- raise ValueError("Unsupported number of stop bits: %r" % self._stopbits)
-
- comDCB.fBinary = 1 # Enable Binary Transmission
- # Char. w/ Parity-Err are replaced with 0xff (if fErrorChar is set to TRUE)
- if self._rtscts:
- comDCB.fRtsControl = win32.RTS_CONTROL_HANDSHAKE
- elif self._rtsToggle:
- comDCB.fRtsControl = win32.RTS_CONTROL_TOGGLE
- else:
- comDCB.fRtsControl = self._rtsState
- if self._dsrdtr:
- comDCB.fDtrControl = win32.DTR_CONTROL_HANDSHAKE
- else:
- comDCB.fDtrControl = self._dtrState
-
- if self._rtsToggle:
- comDCB.fOutxCtsFlow = 0
- else:
- comDCB.fOutxCtsFlow = self._rtscts
- comDCB.fOutxDsrFlow = self._dsrdtr
- comDCB.fOutX = self._xonxoff
- comDCB.fInX = self._xonxoff
- comDCB.fNull = 0
- comDCB.fErrorChar = 0
- comDCB.fAbortOnError = 0
- comDCB.XonChar = XON
- comDCB.XoffChar = XOFF
-
- if not win32.SetCommState(self.hComPort, ctypes.byref(comDCB)):
- raise ValueError("Cannot configure port, some setting was wrong. Original message: %s" % ctypes.WinError())
-
- #~ def __del__(self):
- #~ self.close()
-
- def close(self):
- """Close port"""
- if self._isOpen:
- if self.hComPort:
- # Restore original timeout values:
- win32.SetCommTimeouts(self.hComPort, self._orgTimeouts)
- # Close COM-Port:
- win32.CloseHandle(self.hComPort)
- win32.CloseHandle(self._overlappedRead.hEvent)
- win32.CloseHandle(self._overlappedWrite.hEvent)
- self.hComPort = None
- self._isOpen = False
-
- def makeDeviceName(self, port):
- return device(port)
-
- # - - - - - - - - - - - - - - - - - - - - - - - -
-
- def inWaiting(self):
- """Return the number of characters currently in the input buffer."""
- flags = win32.DWORD()
- comstat = win32.COMSTAT()
- if not win32.ClearCommError(self.hComPort, ctypes.byref(flags), ctypes.byref(comstat)):
- raise SerialException('call to ClearCommError failed')
- return comstat.cbInQue
-
- def read(self, size=1):
- """Read size bytes from the serial port. If a timeout is set it may
- return less characters as requested. With no timeout it will block
- until the requested number of bytes is read."""
- if not self.hComPort: raise portNotOpenError
- if size > 0:
- win32.ResetEvent(self._overlappedRead.hEvent)
- flags = win32.DWORD()
- comstat = win32.COMSTAT()
- if not win32.ClearCommError(self.hComPort, ctypes.byref(flags), ctypes.byref(comstat)):
- raise SerialException('call to ClearCommError failed')
- if self.timeout == 0:
- n = min(comstat.cbInQue, size)
- if n > 0:
- buf = ctypes.create_string_buffer(n)
- rc = win32.DWORD()
- err = win32.ReadFile(self.hComPort, buf, n, ctypes.byref(rc), ctypes.byref(self._overlappedRead))
- if not err and win32.GetLastError() != win32.ERROR_IO_PENDING:
- raise SerialException("ReadFile failed (%s)" % ctypes.WinError())
- err = win32.WaitForSingleObject(self._overlappedRead.hEvent, win32.INFINITE)
- read = buf.raw[:rc.value]
- else:
- read = bytes()
- else:
- buf = ctypes.create_string_buffer(size)
- rc = win32.DWORD()
- err = win32.ReadFile(self.hComPort, buf, size, ctypes.byref(rc), ctypes.byref(self._overlappedRead))
- if not err and win32.GetLastError() != win32.ERROR_IO_PENDING:
- raise SerialException("ReadFile failed (%s)" % ctypes.WinError())
- err = win32.GetOverlappedResult(self.hComPort, ctypes.byref(self._overlappedRead), ctypes.byref(rc), True)
- read = buf.raw[:rc.value]
- else:
- read = bytes()
- return bytes(read)
-
- def write(self, data):
- """Output the given string over the serial port."""
- if not self.hComPort: raise portNotOpenError
- #~ if not isinstance(data, (bytes, bytearray)):
- #~ raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data)))
- # convert data (needed in case of memoryview instance: Py 3.1 io lib), ctypes doesn't like memoryview
- data = bytes(data)
- if data:
- #~ win32event.ResetEvent(self._overlappedWrite.hEvent)
- n = win32.DWORD()
- err = win32.WriteFile(self.hComPort, data, len(data), ctypes.byref(n), self._overlappedWrite)
- if not err and win32.GetLastError() != win32.ERROR_IO_PENDING:
- raise SerialException("WriteFile failed (%s)" % ctypes.WinError())
- if self._writeTimeout != 0: # if blocking (None) or w/ write timeout (>0)
- # Wait for the write to complete.
- #~ win32.WaitForSingleObject(self._overlappedWrite.hEvent, win32.INFINITE)
- err = win32.GetOverlappedResult(self.hComPort, self._overlappedWrite, ctypes.byref(n), True)
- if n.value != len(data):
- raise writeTimeoutError
- return n.value
- else:
- return 0
-
-
- def flushInput(self):
- """Clear input buffer, discarding all that is in the buffer."""
- if not self.hComPort: raise portNotOpenError
- win32.PurgeComm(self.hComPort, win32.PURGE_RXCLEAR | win32.PURGE_RXABORT)
-
- def flushOutput(self):
- """Clear output buffer, aborting the current output and
- discarding all that is in the buffer."""
- if not self.hComPort: raise portNotOpenError
- win32.PurgeComm(self.hComPort, win32.PURGE_TXCLEAR | win32.PURGE_TXABORT)
-
- def sendBreak(self, duration=0.25):
- """Send break condition. Timed, returns to idle state after given duration."""
- if not self.hComPort: raise portNotOpenError
- import time
- win32.SetCommBreak(self.hComPort)
- time.sleep(duration)
- win32.ClearCommBreak(self.hComPort)
-
- def setBreak(self, level=1):
- """Set break: Controls TXD. When active, to transmitting is possible."""
- if not self.hComPort: raise portNotOpenError
- if level:
- win32.SetCommBreak(self.hComPort)
- else:
- win32.ClearCommBreak(self.hComPort)
-
- def setRTS(self, level=1):
- """Set terminal status line: Request To Send"""
- if not self.hComPort: raise portNotOpenError
- if level:
- self._rtsState = win32.RTS_CONTROL_ENABLE
- win32.EscapeCommFunction(self.hComPort, win32.SETRTS)
- else:
- self._rtsState = win32.RTS_CONTROL_DISABLE
- win32.EscapeCommFunction(self.hComPort, win32.CLRRTS)
-
- def setDTR(self, level=1):
- """Set terminal status line: Data Terminal Ready"""
- if not self.hComPort: raise portNotOpenError
- if level:
- self._dtrState = win32.DTR_CONTROL_ENABLE
- win32.EscapeCommFunction(self.hComPort, win32.SETDTR)
- else:
- self._dtrState = win32.DTR_CONTROL_DISABLE
- win32.EscapeCommFunction(self.hComPort, win32.CLRDTR)
-
- def _GetCommModemStatus(self):
- stat = win32.DWORD()
- win32.GetCommModemStatus(self.hComPort, ctypes.byref(stat))
- return stat.value
-
- def getCTS(self):
- """Read terminal status line: Clear To Send"""
- if not self.hComPort: raise portNotOpenError
- return win32.MS_CTS_ON & self._GetCommModemStatus() != 0
-
- def getDSR(self):
- """Read terminal status line: Data Set Ready"""
- if not self.hComPort: raise portNotOpenError
- return win32.MS_DSR_ON & self._GetCommModemStatus() != 0
-
- def getRI(self):
- """Read terminal status line: Ring Indicator"""
- if not self.hComPort: raise portNotOpenError
- return win32.MS_RING_ON & self._GetCommModemStatus() != 0
-
- def getCD(self):
- """Read terminal status line: Carrier Detect"""
- if not self.hComPort: raise portNotOpenError
- return win32.MS_RLSD_ON & self._GetCommModemStatus() != 0
-
- # - - platform specific - - - -
-
- def setXON(self, level=True):
- """Platform specific - set flow state."""
- if not self.hComPort: raise portNotOpenError
- if level:
- win32.EscapeCommFunction(self.hComPort, win32.SETXON)
- else:
- win32.EscapeCommFunction(self.hComPort, win32.SETXOFF)
-
- def outWaiting(self):
- """return how many characters the in the outgoing buffer"""
- flags = win32.DWORD()
- comstat = win32.COMSTAT()
- if not win32.ClearCommError(self.hComPort, ctypes.byref(flags), ctypes.byref(comstat)):
- raise SerialException('call to ClearCommError failed')
- return comstat.cbOutQue
-
- # functions useful for RS-485 adapters
- def setRtsToggle(self, rtsToggle):
- """Change RTS toggle control setting."""
- self._rtsToggle = rtsToggle
- if self._isOpen: self._reconfigurePort()
-
- def getRtsToggle(self):
- """Get the current RTS toggle control setting."""
- return self._rtsToggle
-
- rtsToggle = property(getRtsToggle, setRtsToggle, doc="RTS toggle control setting")
-
-
-# assemble Serial class with the platform specific implementation and the base
-# for file-like behavior. for Python 2.6 and newer, that provide the new I/O
-# library, derive from io.RawIOBase
-try:
- import io
-except ImportError:
- # classic version with our own file-like emulation
- class Serial(Win32Serial, FileLike):
- pass
-else:
- # io library present
- class Serial(Win32Serial, io.RawIOBase):
- pass
-
-
-# Nur Testfunktion!!
-if __name__ == '__main__':
- s = Serial(0)
- sys.stdout.write("%s\n" % s)
-
- s = Serial()
- sys.stdout.write("%s\n" % s)
-
- s.baudrate = 19200
- s.databits = 7
- s.close()
- s.port = 0
- s.open()
- sys.stdout.write("%s\n" % s)
-
diff --git a/python-serial/pyserial/build/lib/serial/sermsdos.py b/python-serial/pyserial/build/lib/serial/sermsdos.py
deleted file mode 100644
index 09a0017..0000000
--- a/python-serial/pyserial/build/lib/serial/sermsdos.py
+++ /dev/null
@@ -1,200 +0,0 @@
-# sermsdos.py
-#
-# History:
-#
-# 3rd September 2002 Dave Haynes
-# 1. First defined
-#
-# Although this code should run under the latest versions of
-# Python, on DOS-based platforms such as Windows 95 and 98,
-# it has been specifically written to be compatible with
-# PyDOS, available at:
-# http://www.python.org/ftp/python/wpy/dos.html
-#
-# PyDOS is a stripped-down version of Python 1.5.2 for
-# DOS machines. Therefore, in making changes to this file,
-# please respect Python 1.5.2 syntax. In addition, please
-# limit the width of this file to 60 characters.
-#
-# Note also that the modules in PyDOS contain fewer members
-# than other versions, so we are restricted to using the
-# following:
-#
-# In module os:
-# -------------
-# environ, chdir, getcwd, getpid, umask, fdopen, close,
-# dup, dup2, fstat, lseek, open, read, write, O_RDONLY,
-# O_WRONLY, O_RDWR, O_APPEND, O_CREAT, O_EXCL, O_TRUNC,
-# access, F_OK, R_OK, W_OK, X_OK, chmod, listdir, mkdir,
-# remove, rename, renames, rmdir, stat, unlink, utime,
-# execl, execle, execlp, execlpe, execvp, execvpe, _exit,
-# system.
-#
-# In module os.path:
-# ------------------
-# curdir, pardir, sep, altsep, pathsep, defpath, linesep.
-#
-
-import os
-import sys
-import string
-import serial.serialutil
-
-BAUD_RATES = {
- 110: "11",
- 150: "15",
- 300: "30",
- 600: "60",
- 1200: "12",
- 2400: "24",
- 4800: "48",
- 9600: "96",
- 19200: "19"}
-
-(PARITY_NONE, PARITY_EVEN, PARITY_ODD, PARITY_MARK,
-PARITY_SPACE) = (0, 1, 2, 3, 4)
-(STOPBITS_ONE, STOPBITS_ONEANDAHALF,
-STOPBITS_TWO) = (1, 1.5, 2)
-FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS = (5, 6, 7, 8)
-(RETURN_ERROR, RETURN_BUSY, RETURN_RETRY, RETURN_READY,
-RETURN_NONE) = ('E', 'B', 'P', 'R', 'N')
-portNotOpenError = ValueError('port not open')
-
-def device(portnum):
- return 'COM%d' % (portnum+1)
-
-class Serial(serialutil.FileLike):
- """
- port: number of device; numbering starts at
- zero. if everything fails, the user can
- specify a device string, note that this
- isn't portable any more
- baudrate: baud rate
- bytesize: number of databits
- parity: enable parity checking
- stopbits: number of stopbits
- timeout: set a timeout (None for waiting forever)
- xonxoff: enable software flow control
- rtscts: enable RTS/CTS flow control
- retry: DOS retry mode
- """
- def __init__(self,
- port,
- baudrate = 9600,
- bytesize = EIGHTBITS,
- parity = PARITY_NONE,
- stopbits = STOPBITS_ONE,
- timeout = None,
- xonxoff = 0,
- rtscts = 0,
- retry = RETURN_RETRY
- ):
-
- if type(port) == type(''):
- # strings are taken directly
- self.portstr = port
- else:
- # numbers are transformed to a string
- self.portstr = device(port+1)
-
- self.baud = BAUD_RATES[baudrate]
- self.bytesize = str(bytesize)
-
- if parity == PARITY_NONE:
- self.parity = 'N'
- elif parity == PARITY_EVEN:
- self.parity = 'E'
- elif parity == PARITY_ODD:
- self.parity = 'O'
- elif parity == PARITY_MARK:
- self.parity = 'M'
- elif parity == PARITY_SPACE:
- self.parity = 'S'
-
- self.stop = str(stopbits)
- self.retry = retry
- self.filename = "sermsdos.tmp"
-
- self._config(self.portstr, self.baud, self.parity,
- self.bytesize, self.stop, self.retry, self.filename)
-
- def __del__(self):
- self.close()
-
- def close(self):
- pass
-
- def _config(self, port, baud, parity, data, stop, retry,
- filename):
- comString = string.join(("MODE ", port, ":"
- , " BAUD= ", baud, " PARITY= ", parity
- , " DATA= ", data, " STOP= ", stop, " RETRY= ",
- retry, " > ", filename ), '')
- os.system(comString)
-
- def setBaudrate(self, baudrate):
- self._config(self.portstr, BAUD_RATES[baudrate],
- self.parity, self.bytesize, self.stop, self.retry,
- self.filename)
-
- def inWaiting(self):
- """returns the number of bytes waiting to be read"""
- raise NotImplementedError
-
- def read(self, num = 1):
- """Read num bytes from serial port"""
- handle = os.open(self.portstr,
- os.O_RDONLY | os.O_BINARY)
- rv = os.read(handle, num)
- os.close(handle)
- return rv
-
- def write(self, s):
- """Write string to serial port"""
- handle = os.open(self.portstr,
- os.O_WRONLY | os.O_BINARY)
- rv = os.write(handle, s)
- os.close(handle)
- return rv
-
- def flushInput(self):
- raise NotImplementedError
-
- def flushOutput(self):
- raise NotImplementedError
-
- def sendBreak(self):
- raise NotImplementedError
-
- def setRTS(self,level=1):
- """Set terminal status line"""
- raise NotImplementedError
-
- def setDTR(self,level=1):
- """Set terminal status line"""
- raise NotImplementedError
-
- def getCTS(self):
- """Eead terminal status line"""
- raise NotImplementedError
-
- def getDSR(self):
- """Eead terminal status line"""
- raise NotImplementedError
-
- def getRI(self):
- """Eead terminal status line"""
- raise NotImplementedError
-
- def getCD(self):
- """Eead terminal status line"""
- raise NotImplementedError
-
- def __repr__(self):
- return string.join(( ": ", self.portstr
- , self.baud, self.parity, self.bytesize, self.stop,
- self.retry , self.filename), ' ')
-
-if __name__ == '__main__':
- s = Serial(0)
- sys.stdio.write('%s %s\n' % (__name__, s))
diff --git a/python-serial/pyserial/build/lib/serial/tools/__init__.py b/python-serial/pyserial/build/lib/serial/tools/__init__.py
deleted file mode 100644
index e69de29..0000000
diff --git a/python-serial/pyserial/build/lib/serial/tools/list_ports.py b/python-serial/pyserial/build/lib/serial/tools/list_ports.py
deleted file mode 100644
index 52eb7a1..0000000
--- a/python-serial/pyserial/build/lib/serial/tools/list_ports.py
+++ /dev/null
@@ -1,99 +0,0 @@
-#!/usr/bin/env python
-
-# portable serial port access with python
-# this is a wrapper module for different platform implementations of the
-# port enumeration feature
-#
-# (C) 2011 Chris Liechti
-# this is distributed under a free software license, see license.txt
-
-"""\
-This module will provide a function called comports that returns an
-iterable (generator or list) that will enumerate available com ports. Note that
-on some systems non-existent ports may be listed.
-
-Additionally a grep function is supplied that can be used to search for ports
-based on their descriptions or hardware ID.
-"""
-
-import sys, os, re
-
-# chose an implementation, depending on os
-#~ if sys.platform == 'cli':
-#~ else:
-import os
-# chose an implementation, depending on os
-if os.name == 'nt': #sys.platform == 'win32':
- from serial.tools.list_ports_windows import *
-elif os.name == 'posix':
- from serial.tools.list_ports_posix import *
-#~ elif os.name == 'java':
-else:
- raise ImportError("Sorry: no implementation for your platform ('%s') available" % (os.name,))
-
-
-def grep(regexp):
- """\
- Search for ports using a regular expression. Port name, description and
- hardware ID are searched. The function returns an iterable that returns the
- same tuples as comport() would do.
- """
- for port, desc, hwid in comports():
- if re.search(regexp, port, re.I) or re.search(regexp, desc) or re.search(regexp, hwid):
- yield port, desc, hwid
-
-
-def main():
- import optparse
-
- parser = optparse.OptionParser(
- usage = "%prog [options] []",
- description = "Miniterm - A simple terminal program for the serial port."
- )
-
- parser.add_option("--debug",
- help="print debug messages and tracebacks (development mode)",
- dest="debug",
- default=False,
- action='store_true')
-
- parser.add_option("-v", "--verbose",
- help="show more messages (can be given multiple times)",
- dest="verbose",
- default=1,
- action='count')
-
- parser.add_option("-q", "--quiet",
- help="suppress all messages",
- dest="verbose",
- action='store_const',
- const=0)
-
- (options, args) = parser.parse_args()
-
-
- hits = 0
- # get iteraror w/ or w/o filter
- if args:
- if len(args) > 1:
- parser.error('more than one regexp not supported')
- print "Filtered list with regexp: %r" % (args[0],)
- iterator = sorted(grep(args[0]))
- else:
- iterator = sorted(comports())
- # list them
- for port, desc, hwid in iterator:
- print "%-20s" % (port,)
- if options.verbose > 1:
- print " desc: %s" % (desc,)
- print " hwid: %s" % (hwid,)
- hits += 1
- if options.verbose:
- if hits:
- print "%d ports found" % (hits,)
- else:
- print "no ports found"
-
-# test
-if __name__ == '__main__':
- main()
diff --git a/python-serial/pyserial/build/lib/serial/tools/list_ports_posix.py b/python-serial/pyserial/build/lib/serial/tools/list_ports_posix.py
deleted file mode 100644
index 8d2357e..0000000
--- a/python-serial/pyserial/build/lib/serial/tools/list_ports_posix.py
+++ /dev/null
@@ -1,197 +0,0 @@
-import glob
-import sys
-import os
-import re
-
-try:
- import subprocess
-except ImportError:
- def popen(argv):
- try:
- si, so = os.popen4(' '.join(argv))
- return so.read().strip()
- except:
- raise IOError('lsusb failed')
-else:
- def popen(argv):
- try:
- return subprocess.check_output(argv, stderr=subprocess.STDOUT).strip()
- except:
- raise IOError('lsusb failed')
-
-
-# The comports function is expected to return an iterable that yields tuples of
-# 3 strings: port name, human readable description and a hardware ID.
-#
-# as currently no method is known to get the second two strings easily, they
-# are currently just identical to the port name.
-
-# try to detect the OS so that a device can be selected...
-plat = sys.platform.lower()
-
-def read_line(filename):
- """help function to read a single line from a file. returns none"""
- try:
- f = open(filename)
- line = f.readline().strip()
- f.close()
- return line
- except IOError:
- return None
-
-def re_group(regexp, text):
- """search for regexp in text, return 1st group on match"""
- m = re.search(regexp, text)
- if m: return m.group(1)
-
-
-if plat[:5] == 'linux': # Linux (confirmed)
- # try to extract descriptions from sysfs. this was done by experimenting,
- # no guarantee that it works for all devices or in the future...
-
- def usb_sysfs_hw_string(sysfs_path):
- """given a path to a usb device in sysfs, return a string describing it"""
- bus, dev = os.path.basename(os.path.realpath(sysfs_path)).split('-')
- snr = read_line(sysfs_path+'/serial')
- if snr:
- snr_txt = ' SNR=%s' % (snr,)
- else:
- snr_txt = ''
- return 'USB VID:PID=%s:%s%s' % (
- read_line(sysfs_path+'/idVendor'),
- read_line(sysfs_path+'/idProduct'),
- snr_txt
- )
-
- def usb_lsusb_string(sysfs_path):
- bus, dev = os.path.basename(os.path.realpath(sysfs_path)).split('-')
- try:
- desc = popen(['lsusb', '-v', '-s', '%s:%s' % (bus, dev)])
- # descriptions from device
- iManufacturer = re_group('iManufacturer\s+\w+ (.+)', desc)
- iProduct = re_group('iProduct\s+\w+ (.+)', desc)
- iSerial = re_group('iSerial\s+\w+ (.+)', desc) or ''
- # descriptions from kernel
- idVendor = re_group('idVendor\s+0x\w+ (.+)', desc)
- idProduct = re_group('idProduct\s+0x\w+ (.+)', desc)
- # create descriptions. prefer text from device, fall back to the others
- return '%s %s %s' % (iManufacturer or idVendor, iProduct or idProduct, iSerial)
- except IOError:
- return base
-
- def describe(device):
- """\
- Get a human readable description.
- For USB-Serial devices try to run lsusb to get a human readable description.
- For USB-CDC devices read the description from sysfs.
- """
- base = os.path.basename(device)
- # USB-Serial devices
- sys_dev_path = '/sys/class/tty/%s/device/driver/%s' % (base, base)
- if os.path.exists(sys_dev_path):
- sys_usb = os.path.dirname(os.path.dirname(os.path.realpath(sys_dev_path)))
- return usb_lsusb_string(sys_usb)
- # USB-CDC devices
- sys_dev_path = '/sys/class/tty/%s/device/interface' % (base,)
- if os.path.exists(sys_dev_path):
- return read_line(sys_dev_path)
- return base
-
- def hwinfo(device):
- """Try to get a HW identification using sysfs"""
- base = os.path.basename(device)
- if os.path.exists('/sys/class/tty/%s/device' % (base,)):
- # PCI based devices
- sys_id_path = '/sys/class/tty/%s/device/id' % (base,)
- if os.path.exists(sys_id_path):
- return read_line(sys_id_path)
- # USB-Serial devices
- sys_dev_path = '/sys/class/tty/%s/device/driver/%s' % (base, base)
- if os.path.exists(sys_dev_path):
- sys_usb = os.path.dirname(os.path.dirname(os.path.realpath(sys_dev_path)))
- return usb_sysfs_hw_string(sys_usb)
- # USB-CDC devices
- if base.startswith('ttyACM'):
- sys_dev_path = '/sys/class/tty/%s/device' % (base,)
- if os.path.exists(sys_dev_path):
- return usb_sysfs_hw_string(sys_dev_path + '/..')
- return 'n/a' # XXX directly remove these from the list?
-
- def comports():
- devices = glob.glob('/dev/ttyS*') + glob.glob('/dev/ttyUSB*') + glob.glob('/dev/ttyACM*')
- return [(d, describe(d), hwinfo(d)) for d in devices]
-
-elif plat == 'cygwin': # cygwin/win32
- def comports():
- devices = glob.glob('/dev/com*')
- return [(d, d, d) for d in devices]
-
-elif plat == 'openbsd3': # BSD
- def comports():
- devices = glob.glob('/dev/ttyp*')
- return [(d, d, d) for d in devices]
-
-elif plat[:3] == 'bsd' or \
- plat[:7] == 'freebsd' or \
- plat[:7] == 'openbsd': # BSD
-
- def comports():
- devices = glob.glob('/dev/cuad*')
- return [(d, d, d) for d in devices]
-
-elif plat[:6] == 'darwin': # OS X (confirmed)
- def comports():
- """scan for available ports. return a list of device names."""
- devices = glob.glob('/dev/tty.*')
- return [(d, d, d) for d in devices]
-
-elif plat[:6] == 'netbsd': # NetBSD
- def comports():
- """scan for available ports. return a list of device names."""
- devices = glob.glob('/dev/dty*')
- return [(d, d, d) for d in devices]
-
-elif plat[:4] == 'irix': # IRIX
- def comports():
- """scan for available ports. return a list of device names."""
- devices = glob.glob('/dev/ttyf*')
- return [(d, d, d) for d in devices]
-
-elif plat[:2] == 'hp': # HP-UX (not tested)
- def comports():
- """scan for available ports. return a list of device names."""
- devices = glob.glob('/dev/tty*p0')
- return [(d, d, d) for d in devices]
-
-elif plat[:5] == 'sunos': # Solaris/SunOS
- def comports():
- """scan for available ports. return a list of device names."""
- devices = glob.glob('/dev/tty*c')
- return [(d, d, d) for d in devices]
-
-elif plat[:3] == 'aix': # AIX
- def comports():
- """scan for available ports. return a list of device names."""
- devices = glob.glob('/dev/tty*')
- return [(d, d, d) for d in devices]
-
-else:
- # platform detection has failed...
- sys.stderr.write("""\
-don't know how to enumerate ttys on this system.
-! I you know how the serial ports are named send this information to
-! the author of this module:
-
-sys.platform = %r
-os.name = %r
-pySerial version = %s
-
-also add the naming scheme of the serial ports and with a bit luck you can get
-this module running...
-""" % (sys.platform, os.name, serial.VERSION))
- raise ImportError("Sorry: no implementation for your platform ('%s') available" % (os.name,))
-
-# test
-if __name__ == '__main__':
- for port, desc, hwid in sorted(comports()):
- print "%s: %s [%s]" % (port, desc, hwid)
diff --git a/python-serial/pyserial/build/lib/serial/tools/list_ports_windows.py b/python-serial/pyserial/build/lib/serial/tools/list_ports_windows.py
deleted file mode 100644
index 5b3420d..0000000
--- a/python-serial/pyserial/build/lib/serial/tools/list_ports_windows.py
+++ /dev/null
@@ -1,209 +0,0 @@
-import ctypes
-import re
-
-def ValidHandle(value, func, arguments):
- if value == 0:
- raise ctypes.WinError()
- return value
-
-import serial
-from serial.win32 import ULONG_PTR, is_64bit
-from ctypes.wintypes import HANDLE
-from ctypes.wintypes import BOOL
-from ctypes.wintypes import HWND
-from ctypes.wintypes import DWORD
-from ctypes.wintypes import WORD
-from ctypes.wintypes import LONG
-from ctypes.wintypes import ULONG
-from ctypes.wintypes import LPCSTR
-from ctypes.wintypes import HKEY
-from ctypes.wintypes import BYTE
-
-NULL = 0
-HDEVINFO = ctypes.c_void_p
-PCTSTR = ctypes.c_char_p
-CHAR = ctypes.c_char
-LPDWORD = PDWORD = ctypes.POINTER(DWORD)
-#~ LPBYTE = PBYTE = ctypes.POINTER(BYTE)
-LPBYTE = PBYTE = ctypes.c_void_p # XXX avoids error about types
-PHKEY = ctypes.POINTER(HKEY)
-
-ACCESS_MASK = DWORD
-REGSAM = ACCESS_MASK
-
-
-def byte_buffer(length):
- """Get a buffer for a string"""
- return (BYTE*length)()
-
-def string(buffer):
- s = []
- for c in buffer:
- if c == 0: break
- s.append(chr(c & 0xff)) # "& 0xff": hack to convert signed to unsigned
- return ''.join(s)
-
-
-class GUID(ctypes.Structure):
- _fields_ = [
- ('Data1', DWORD),
- ('Data2', WORD),
- ('Data3', WORD),
- ('Data4', BYTE*8),
- ]
- def __str__(self):
- return "{%08x-%04x-%04x-%s-%s}" % (
- self.Data1,
- self.Data2,
- self.Data3,
- ''.join(["%02x" % d for d in self.Data4[:2]]),
- ''.join(["%02x" % d for d in self.Data4[2:]]),
- )
-
-class SP_DEVINFO_DATA(ctypes.Structure):
- _fields_ = [
- ('cbSize', DWORD),
- ('ClassGuid', GUID),
- ('DevInst', DWORD),
- ('Reserved', ULONG_PTR),
- ]
- def __str__(self):
- return "ClassGuid:%s DevInst:%s" % (self.ClassGuid, self.DevInst)
-PSP_DEVINFO_DATA = ctypes.POINTER(SP_DEVINFO_DATA)
-
-class SP_DEVICE_INTERFACE_DATA(ctypes.Structure):
- _fields_ = [
- ('cbSize', DWORD),
- ('InterfaceClassGuid', GUID),
- ('Flags', DWORD),
- ('Reserved', ULONG_PTR),
- ]
- def __str__(self):
- return "InterfaceClassGuid:%s Flags:%s" % (self.InterfaceClassGuid, self.Flags)
-PSP_DEVICE_INTERFACE_DATA = ctypes.POINTER(SP_DEVICE_INTERFACE_DATA)
-
-PSP_DEVICE_INTERFACE_DETAIL_DATA = ctypes.c_void_p
-
-setupapi = ctypes.windll.LoadLibrary("setupapi")
-SetupDiDestroyDeviceInfoList = setupapi.SetupDiDestroyDeviceInfoList
-SetupDiDestroyDeviceInfoList.argtypes = [HDEVINFO]
-SetupDiDestroyDeviceInfoList.restype = BOOL
-
-SetupDiGetClassDevs = setupapi.SetupDiGetClassDevsA
-SetupDiGetClassDevs.argtypes = [ctypes.POINTER(GUID), PCTSTR, HWND, DWORD]
-SetupDiGetClassDevs.restype = HDEVINFO
-SetupDiGetClassDevs.errcheck = ValidHandle
-
-SetupDiEnumDeviceInterfaces = setupapi.SetupDiEnumDeviceInterfaces
-SetupDiEnumDeviceInterfaces.argtypes = [HDEVINFO, PSP_DEVINFO_DATA, ctypes.POINTER(GUID), DWORD, PSP_DEVICE_INTERFACE_DATA]
-SetupDiEnumDeviceInterfaces.restype = BOOL
-
-SetupDiGetDeviceInterfaceDetail = setupapi.SetupDiGetDeviceInterfaceDetailA
-SetupDiGetDeviceInterfaceDetail.argtypes = [HDEVINFO, PSP_DEVICE_INTERFACE_DATA, PSP_DEVICE_INTERFACE_DETAIL_DATA, DWORD, PDWORD, PSP_DEVINFO_DATA]
-SetupDiGetDeviceInterfaceDetail.restype = BOOL
-
-SetupDiGetDeviceRegistryProperty = setupapi.SetupDiGetDeviceRegistryPropertyA
-SetupDiGetDeviceRegistryProperty.argtypes = [HDEVINFO, PSP_DEVINFO_DATA, DWORD, PDWORD, PBYTE, DWORD, PDWORD]
-SetupDiGetDeviceRegistryProperty.restype = BOOL
-
-SetupDiOpenDevRegKey = setupapi.SetupDiOpenDevRegKey
-SetupDiOpenDevRegKey.argtypes = [HDEVINFO, PSP_DEVINFO_DATA, DWORD, DWORD, DWORD, REGSAM]
-SetupDiOpenDevRegKey.restype = HKEY
-
-advapi32 = ctypes.windll.LoadLibrary("Advapi32")
-RegCloseKey = advapi32.RegCloseKey
-RegCloseKey.argtypes = [HKEY]
-RegCloseKey.restype = LONG
-
-RegQueryValueEx = advapi32.RegQueryValueExA
-RegQueryValueEx.argtypes = [HKEY, LPCSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD]
-RegQueryValueEx.restype = LONG
-
-
-GUID_CLASS_COMPORT = GUID(0x86e0d1e0L, 0x8089, 0x11d0,
- (BYTE*8)(0x9c, 0xe4, 0x08, 0x00, 0x3e, 0x30, 0x1f, 0x73))
-
-DIGCF_PRESENT = 2
-DIGCF_DEVICEINTERFACE = 16
-INVALID_HANDLE_VALUE = 0
-ERROR_INSUFFICIENT_BUFFER = 122
-SPDRP_HARDWAREID = 1
-SPDRP_FRIENDLYNAME = 12
-ERROR_NO_MORE_ITEMS = 259
-DICS_FLAG_GLOBAL = 1
-DIREG_DEV = 0x00000001
-KEY_READ = 0x20019
-REG_SZ = 1
-
-# workaround for compatibility between Python 2.x and 3.x
-PortName = serial.to_bytes([80, 111, 114, 116, 78, 97, 109, 101]) # "PortName"
-
-def comports():
- """This generator scans the device registry for com ports and yields port, desc, hwid"""
- g_hdi = SetupDiGetClassDevs(ctypes.byref(GUID_CLASS_COMPORT), None, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE);
- #~ for i in range(256):
- for dwIndex in range(256):
- did = SP_DEVICE_INTERFACE_DATA()
- did.cbSize = ctypes.sizeof(did)
-
- if not SetupDiEnumDeviceInterfaces(g_hdi, None, ctypes.byref(GUID_CLASS_COMPORT), dwIndex, ctypes.byref(did)):
- if ctypes.GetLastError() != ERROR_NO_MORE_ITEMS:
- raise ctypes.WinError()
- break
-
- dwNeeded = DWORD()
- # get the size
- if not SetupDiGetDeviceInterfaceDetail(g_hdi, ctypes.byref(did), None, 0, ctypes.byref(dwNeeded), None):
- # Ignore ERROR_INSUFFICIENT_BUFFER
- if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER:
- raise ctypes.WinError()
- # allocate buffer
- class SP_DEVICE_INTERFACE_DETAIL_DATA_A(ctypes.Structure):
- _fields_ = [
- ('cbSize', DWORD),
- ('DevicePath', CHAR*(dwNeeded.value - ctypes.sizeof(DWORD))),
- ]
- def __str__(self):
- return "DevicePath:%s" % (self.DevicePath,)
- idd = SP_DEVICE_INTERFACE_DETAIL_DATA_A()
- if is_64bit():
- idd.cbSize = 8
- else:
- idd.cbSize = 5
- devinfo = SP_DEVINFO_DATA()
- devinfo.cbSize = ctypes.sizeof(devinfo)
- if not SetupDiGetDeviceInterfaceDetail(g_hdi, ctypes.byref(did), ctypes.byref(idd), dwNeeded, None, ctypes.byref(devinfo)):
- raise ctypes.WinError()
-
- # hardware ID
- szHardwareID = byte_buffer(250)
- if not SetupDiGetDeviceRegistryProperty(g_hdi, ctypes.byref(devinfo), SPDRP_HARDWAREID, None, ctypes.byref(szHardwareID), ctypes.sizeof(szHardwareID) - 1, None):
- # Ignore ERROR_INSUFFICIENT_BUFFER
- if GetLastError() != ERROR_INSUFFICIENT_BUFFER:
- raise ctypes.WinError()
-
- # friendly name
- szFriendlyName = byte_buffer(250)
- if not SetupDiGetDeviceRegistryProperty(g_hdi, ctypes.byref(devinfo), SPDRP_FRIENDLYNAME, None, ctypes.byref(szFriendlyName), ctypes.sizeof(szFriendlyName) - 1, None):
- # Ignore ERROR_INSUFFICIENT_BUFFER
- if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER:
- #~ raise IOError("failed to get details for %s (%s)" % (devinfo, szHardwareID.value))
- port_name = None
- else:
- # the real com port name has to read differently...
- hkey = SetupDiOpenDevRegKey(g_hdi, ctypes.byref(devinfo), DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ)
- port_name_buffer = byte_buffer(250)
- port_name_length = ULONG(ctypes.sizeof(port_name_buffer))
- RegQueryValueEx(hkey, PortName, None, None, ctypes.byref(port_name_buffer), ctypes.byref(port_name_length))
- RegCloseKey(hkey)
- yield string(port_name_buffer), string(szFriendlyName), string(szHardwareID)
-
- SetupDiDestroyDeviceInfoList(g_hdi)
-
-
-# test
-if __name__ == '__main__':
- import serial
-
- for port, desc, hwid in sorted(comports()):
- print "%s: %s [%s]" % (port, desc, hwid)
diff --git a/python-serial/pyserial/build/lib/serial/tools/miniterm.py b/python-serial/pyserial/build/lib/serial/tools/miniterm.py
deleted file mode 100644
index 5d794fa..0000000
--- a/python-serial/pyserial/build/lib/serial/tools/miniterm.py
+++ /dev/null
@@ -1,645 +0,0 @@
-#!/usr/bin/env python
-
-# Very simple serial terminal
-# (C)2002-2011 Chris Liechti
-
-# Input characters are sent directly (only LF -> CR/LF/CRLF translation is
-# done), received characters are displayed as is (or escaped trough pythons
-# repr, useful for debug purposes)
-
-
-import sys, os, serial, threading
-
-EXITCHARCTER = '\x1d' # GS/CTRL+]
-MENUCHARACTER = '\x14' # Menu: CTRL+T
-
-
-def key_description(character):
- """generate a readable description for a key"""
- ascii_code = ord(character)
- if ascii_code < 32:
- return 'Ctrl+%c' % (ord('@') + ascii_code)
- else:
- return repr(character)
-
-
-# help text, starts with blank line! it's a function so that the current values
-# for the shortcut keys is used and not the value at program start
-def get_help_text():
- return """
---- pySerial (%(version)s) - miniterm - help
----
---- %(exit)-8s Exit program
---- %(menu)-8s Menu escape key, followed by:
---- Menu keys:
---- %(itself)-7s Send the menu character itself to remote
---- %(exchar)-7s Send the exit character itself to remote
---- %(info)-7s Show info
---- %(upload)-7s Upload file (prompt will be shown)
---- Toggles:
---- %(rts)-7s RTS %(echo)-7s local echo
---- %(dtr)-7s DTR %(break)-7s BREAK
---- %(lfm)-7s line feed %(repr)-7s Cycle repr mode
----
---- Port settings (%(menu)s followed by the following):
---- p change port
---- 7 8 set data bits
---- n e o s m change parity (None, Even, Odd, Space, Mark)
---- 1 2 3 set stop bits (1, 2, 1.5)
---- b change baud rate
---- x X disable/enable software flow control
---- r R disable/enable hardware flow control
-""" % {
- 'version': getattr(serial, 'VERSION', 'unknown version'),
- 'exit': key_description(EXITCHARCTER),
- 'menu': key_description(MENUCHARACTER),
- 'rts': key_description('\x12'),
- 'repr': key_description('\x01'),
- 'dtr': key_description('\x04'),
- 'lfm': key_description('\x0c'),
- 'break': key_description('\x02'),
- 'echo': key_description('\x05'),
- 'info': key_description('\x09'),
- 'upload': key_description('\x15'),
- 'itself': key_description(MENUCHARACTER),
- 'exchar': key_description(EXITCHARCTER),
-}
-
-if sys.version_info >= (3, 0):
- def character(b):
- return b.decode('latin1')
-else:
- def character(b):
- return b
-
-# first choose a platform dependant way to read single characters from the console
-global console
-
-if os.name == 'nt':
- import msvcrt
- class Console(object):
- def __init__(self):
- pass
-
- def setup(self):
- pass # Do nothing for 'nt'
-
- def cleanup(self):
- pass # Do nothing for 'nt'
-
- def getkey(self):
- while True:
- z = msvcrt.getch()
- if z == '\0' or z == '\xe0': # functions keys, ignore
- msvcrt.getch()
- else:
- if z == '\r':
- return '\n'
- return z
-
- console = Console()
-
-elif os.name == 'posix':
- import termios, sys, os
- class Console(object):
- def __init__(self):
- self.fd = sys.stdin.fileno()
-
- def setup(self):
- self.old = termios.tcgetattr(self.fd)
- new = termios.tcgetattr(self.fd)
- new[3] = new[3] & ~termios.ICANON & ~termios.ECHO & ~termios.ISIG
- new[6][termios.VMIN] = 1
- new[6][termios.VTIME] = 0
- termios.tcsetattr(self.fd, termios.TCSANOW, new)
-
- def getkey(self):
- c = os.read(self.fd, 1)
- return c
-
- def cleanup(self):
- termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old)
-
- console = Console()
-
- def cleanup_console():
- console.cleanup()
-
- console.setup()
- sys.exitfunc = cleanup_console # terminal modes have to be restored on exit...
-
-else:
- raise NotImplementedError("Sorry no implementation for your platform (%s) available." % sys.platform)
-
-
-CONVERT_CRLF = 2
-CONVERT_CR = 1
-CONVERT_LF = 0
-NEWLINE_CONVERISON_MAP = ('\n', '\r', '\r\n')
-LF_MODES = ('LF', 'CR', 'CR/LF')
-
-REPR_MODES = ('raw', 'some control', 'all control', 'hex')
-
-class Miniterm(object):
- def __init__(self, port, baudrate, parity, rtscts, xonxoff, echo=False, convert_outgoing=CONVERT_CRLF, repr_mode=0):
- try:
- self.serial = serial.serial_for_url(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1)
- except AttributeError:
- # happens when the installed pyserial is older than 2.5. use the
- # Serial class directly then.
- self.serial = serial.Serial(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1)
- self.echo = echo
- self.repr_mode = repr_mode
- self.convert_outgoing = convert_outgoing
- self.newline = NEWLINE_CONVERISON_MAP[self.convert_outgoing]
- self.dtr_state = True
- self.rts_state = True
- self.break_state = False
-
- def _start_reader(self):
- """Start reader thread"""
- self._reader_alive = True
- # start serial->console thread
- self.receiver_thread = threading.Thread(target=self.reader)
- self.receiver_thread.setDaemon(True)
- self.receiver_thread.start()
-
- def _stop_reader(self):
- """Stop reader thread only, wait for clean exit of thread"""
- self._reader_alive = False
- self.receiver_thread.join()
-
-
- def start(self):
- self.alive = True
- self._start_reader()
- # enter console->serial loop
- self.transmitter_thread = threading.Thread(target=self.writer)
- self.transmitter_thread.setDaemon(True)
- self.transmitter_thread.start()
-
- def stop(self):
- self.alive = False
-
- def join(self, transmit_only=False):
- self.transmitter_thread.join()
- if not transmit_only:
- self.receiver_thread.join()
-
- def dump_port_settings(self):
- sys.stderr.write("\n--- Settings: %s %s,%s,%s,%s\n" % (
- self.serial.portstr,
- self.serial.baudrate,
- self.serial.bytesize,
- self.serial.parity,
- self.serial.stopbits))
- sys.stderr.write('--- RTS: %-8s DTR: %-8s BREAK: %-8s\n' % (
- (self.rts_state and 'active' or 'inactive'),
- (self.dtr_state and 'active' or 'inactive'),
- (self.break_state and 'active' or 'inactive')))
- try:
- sys.stderr.write('--- CTS: %-8s DSR: %-8s RI: %-8s CD: %-8s\n' % (
- (self.serial.getCTS() and 'active' or 'inactive'),
- (self.serial.getDSR() and 'active' or 'inactive'),
- (self.serial.getRI() and 'active' or 'inactive'),
- (self.serial.getCD() and 'active' or 'inactive')))
- except serial.SerialException:
- # on RFC 2217 ports it can happen to no modem state notification was
- # yet received. ignore this error.
- pass
- sys.stderr.write('--- software flow control: %s\n' % (self.serial.xonxoff and 'active' or 'inactive'))
- sys.stderr.write('--- hardware flow control: %s\n' % (self.serial.rtscts and 'active' or 'inactive'))
- sys.stderr.write('--- data escaping: %s linefeed: %s\n' % (
- REPR_MODES[self.repr_mode],
- LF_MODES[self.convert_outgoing]))
-
- def reader(self):
- """loop and copy serial->console"""
- try:
- while self.alive and self._reader_alive:
- data = character(self.serial.read(1))
-
- if self.repr_mode == 0:
- # direct output, just have to care about newline setting
- if data == '\r' and self.convert_outgoing == CONVERT_CR:
- sys.stdout.write('\n')
- else:
- sys.stdout.write(data)
- elif self.repr_mode == 1:
- # escape non-printable, let pass newlines
- if self.convert_outgoing == CONVERT_CRLF and data in '\r\n':
- if data == '\n':
- sys.stdout.write('\n')
- elif data == '\r':
- pass
- elif data == '\n' and self.convert_outgoing == CONVERT_LF:
- sys.stdout.write('\n')
- elif data == '\r' and self.convert_outgoing == CONVERT_CR:
- sys.stdout.write('\n')
- else:
- sys.stdout.write(repr(data)[1:-1])
- elif self.repr_mode == 2:
- # escape all non-printable, including newline
- sys.stdout.write(repr(data)[1:-1])
- elif self.repr_mode == 3:
- # escape everything (hexdump)
- for c in data:
- sys.stdout.write("%s " % c.encode('hex'))
- sys.stdout.flush()
- except serial.SerialException, e:
- self.alive = False
- # would be nice if the console reader could be interruptted at this
- # point...
- raise
-
-
- def writer(self):
- """\
- Loop and copy console->serial until EXITCHARCTER character is
- found. When MENUCHARACTER is found, interpret the next key
- locally.
- """
- menu_active = False
- try:
- while self.alive:
- try:
- b = console.getkey()
- except KeyboardInterrupt:
- b = serial.to_bytes([3])
- c = character(b)
- if menu_active:
- if c == MENUCHARACTER or c == EXITCHARCTER: # Menu character again/exit char -> send itself
- self.serial.write(b) # send character
- if self.echo:
- sys.stdout.write(c)
- elif c == '\x15': # CTRL+U -> upload file
- sys.stderr.write('\n--- File to upload: ')
- sys.stderr.flush()
- console.cleanup()
- filename = sys.stdin.readline().rstrip('\r\n')
- if filename:
- try:
- file = open(filename, 'r')
- sys.stderr.write('--- Sending file %s ---\n' % filename)
- while True:
- line = file.readline().rstrip('\r\n')
- if not line:
- break
- self.serial.write(line)
- self.serial.write('\r\n')
- # Wait for output buffer to drain.
- self.serial.flush()
- sys.stderr.write('.') # Progress indicator.
- sys.stderr.write('\n--- File %s sent ---\n' % filename)
- except IOError, e:
- sys.stderr.write('--- ERROR opening file %s: %s ---\n' % (filename, e))
- console.setup()
- elif c in '\x08hH?': # CTRL+H, h, H, ? -> Show help
- sys.stderr.write(get_help_text())
- elif c == '\x12': # CTRL+R -> Toggle RTS
- self.rts_state = not self.rts_state
- self.serial.setRTS(self.rts_state)
- sys.stderr.write('--- RTS %s ---\n' % (self.rts_state and 'active' or 'inactive'))
- elif c == '\x04': # CTRL+D -> Toggle DTR
- self.dtr_state = not self.dtr_state
- self.serial.setDTR(self.dtr_state)
- sys.stderr.write('--- DTR %s ---\n' % (self.dtr_state and 'active' or 'inactive'))
- elif c == '\x02': # CTRL+B -> toggle BREAK condition
- self.break_state = not self.break_state
- self.serial.setBreak(self.break_state)
- sys.stderr.write('--- BREAK %s ---\n' % (self.break_state and 'active' or 'inactive'))
- elif c == '\x05': # CTRL+E -> toggle local echo
- self.echo = not self.echo
- sys.stderr.write('--- local echo %s ---\n' % (self.echo and 'active' or 'inactive'))
- elif c == '\x09': # CTRL+I -> info
- self.dump_port_settings()
- elif c == '\x01': # CTRL+A -> cycle escape mode
- self.repr_mode += 1
- if self.repr_mode > 3:
- self.repr_mode = 0
- sys.stderr.write('--- escape data: %s ---\n' % (
- REPR_MODES[self.repr_mode],
- ))
- elif c == '\x0c': # CTRL+L -> cycle linefeed mode
- self.convert_outgoing += 1
- if self.convert_outgoing > 2:
- self.convert_outgoing = 0
- self.newline = NEWLINE_CONVERISON_MAP[self.convert_outgoing]
- sys.stderr.write('--- line feed %s ---\n' % (
- LF_MODES[self.convert_outgoing],
- ))
- elif c in 'pP': # P -> change port
- sys.stderr.write('\n--- Enter port name: ')
- sys.stderr.flush()
- console.cleanup()
- try:
- port = sys.stdin.readline().strip()
- except KeyboardInterrupt:
- port = None
- console.setup()
- if port and port != self.serial.port:
- # reader thread needs to be shut down
- self._stop_reader()
- # save settings
- settings = self.serial.getSettingsDict()
- try:
- try:
- new_serial = serial.serial_for_url(port, do_not_open=True)
- except AttributeError:
- # happens when the installed pyserial is older than 2.5. use the
- # Serial class directly then.
- new_serial = serial.Serial()
- new_serial.port = port
- # restore settings and open
- new_serial.applySettingsDict(settings)
- new_serial.open()
- new_serial.setRTS(self.rts_state)
- new_serial.setDTR(self.dtr_state)
- new_serial.setBreak(self.break_state)
- except Exception, e:
- sys.stderr.write('--- ERROR opening new port: %s ---\n' % (e,))
- new_serial.close()
- else:
- self.serial.close()
- self.serial = new_serial
- sys.stderr.write('--- Port changed to: %s ---\n' % (self.serial.port,))
- # and restart the reader thread
- self._start_reader()
- elif c in 'bB': # B -> change baudrate
- sys.stderr.write('\n--- Baudrate: ')
- sys.stderr.flush()
- console.cleanup()
- backup = self.serial.baudrate
- try:
- self.serial.baudrate = int(sys.stdin.readline().strip())
- except ValueError, e:
- sys.stderr.write('--- ERROR setting baudrate: %s ---\n' % (e,))
- self.serial.baudrate = backup
- else:
- self.dump_port_settings()
- console.setup()
- elif c == '8': # 8 -> change to 8 bits
- self.serial.bytesize = serial.EIGHTBITS
- self.dump_port_settings()
- elif c == '7': # 7 -> change to 8 bits
- self.serial.bytesize = serial.SEVENBITS
- self.dump_port_settings()
- elif c in 'eE': # E -> change to even parity
- self.serial.parity = serial.PARITY_EVEN
- self.dump_port_settings()
- elif c in 'oO': # O -> change to odd parity
- self.serial.parity = serial.PARITY_ODD
- self.dump_port_settings()
- elif c in 'mM': # M -> change to mark parity
- self.serial.parity = serial.PARITY_MARK
- self.dump_port_settings()
- elif c in 'sS': # S -> change to space parity
- self.serial.parity = serial.PARITY_SPACE
- self.dump_port_settings()
- elif c in 'nN': # N -> change to no parity
- self.serial.parity = serial.PARITY_NONE
- self.dump_port_settings()
- elif c == '1': # 1 -> change to 1 stop bits
- self.serial.stopbits = serial.STOPBITS_ONE
- self.dump_port_settings()
- elif c == '2': # 2 -> change to 2 stop bits
- self.serial.stopbits = serial.STOPBITS_TWO
- self.dump_port_settings()
- elif c == '3': # 3 -> change to 1.5 stop bits
- self.serial.stopbits = serial.STOPBITS_ONE_POINT_FIVE
- self.dump_port_settings()
- elif c in 'xX': # X -> change software flow control
- self.serial.xonxoff = (c == 'X')
- self.dump_port_settings()
- elif c in 'rR': # R -> change hardware flow control
- self.serial.rtscts = (c == 'R')
- self.dump_port_settings()
- else:
- sys.stderr.write('--- unknown menu character %s --\n' % key_description(c))
- menu_active = False
- elif c == MENUCHARACTER: # next char will be for menu
- menu_active = True
- elif c == EXITCHARCTER:
- self.stop()
- break # exit app
- elif c == '\n':
- self.serial.write(self.newline) # send newline character(s)
- if self.echo:
- sys.stdout.write(c) # local echo is a real newline in any case
- sys.stdout.flush()
- else:
- self.serial.write(b) # send byte
- if self.echo:
- sys.stdout.write(c)
- sys.stdout.flush()
- except:
- self.alive = False
- raise
-
-def main():
- import optparse
-
- parser = optparse.OptionParser(
- usage = "%prog [options] [port [baudrate]]",
- description = "Miniterm - A simple terminal program for the serial port."
- )
-
- parser.add_option("-p", "--port",
- dest = "port",
- help = "port, a number or a device name. (deprecated option, use parameter instead)",
- default = None
- )
-
- parser.add_option("-b", "--baud",
- dest = "baudrate",
- action = "store",
- type = 'int',
- help = "set baud rate, default %default",
- default = 9600
- )
-
- parser.add_option("--parity",
- dest = "parity",
- action = "store",
- help = "set parity, one of [N, E, O, S, M], default=N",
- default = 'N'
- )
-
- parser.add_option("-e", "--echo",
- dest = "echo",
- action = "store_true",
- help = "enable local echo (default off)",
- default = False
- )
-
- parser.add_option("--rtscts",
- dest = "rtscts",
- action = "store_true",
- help = "enable RTS/CTS flow control (default off)",
- default = False
- )
-
- parser.add_option("--xonxoff",
- dest = "xonxoff",
- action = "store_true",
- help = "enable software flow control (default off)",
- default = False
- )
-
- parser.add_option("--cr",
- dest = "cr",
- action = "store_true",
- help = "do not send CR+LF, send CR only",
- default = False
- )
-
- parser.add_option("--lf",
- dest = "lf",
- action = "store_true",
- help = "do not send CR+LF, send LF only",
- default = False
- )
-
- parser.add_option("-D", "--debug",
- dest = "repr_mode",
- action = "count",
- help = """debug received data (escape non-printable chars)
---debug can be given multiple times:
-0: just print what is received
-1: escape non-printable characters, do newlines as unusual
-2: escape non-printable characters, newlines too
-3: hex dump everything""",
- default = 0
- )
-
- parser.add_option("--rts",
- dest = "rts_state",
- action = "store",
- type = 'int',
- help = "set initial RTS line state (possible values: 0, 1)",
- default = None
- )
-
- parser.add_option("--dtr",
- dest = "dtr_state",
- action = "store",
- type = 'int',
- help = "set initial DTR line state (possible values: 0, 1)",
- default = None
- )
-
- parser.add_option("-q", "--quiet",
- dest = "quiet",
- action = "store_true",
- help = "suppress non error messages",
- default = False
- )
-
- parser.add_option("--exit-char",
- dest = "exit_char",
- action = "store",
- type = 'int',
- help = "ASCII code of special character that is used to exit the application",
- default = 0x1d
- )
-
- parser.add_option("--menu-char",
- dest = "menu_char",
- action = "store",
- type = 'int',
- help = "ASCII code of special character that is used to control miniterm (menu)",
- default = 0x14
- )
-
- (options, args) = parser.parse_args()
-
- options.parity = options.parity.upper()
- if options.parity not in 'NEOSM':
- parser.error("invalid parity")
-
- if options.cr and options.lf:
- parser.error("only one of --cr or --lf can be specified")
-
- if options.menu_char == options.exit_char:
- parser.error('--exit-char can not be the same as --menu-char')
-
- global EXITCHARCTER, MENUCHARACTER
- EXITCHARCTER = chr(options.exit_char)
- MENUCHARACTER = chr(options.menu_char)
-
- port = options.port
- baudrate = options.baudrate
- if args:
- if options.port is not None:
- parser.error("no arguments are allowed, options only when --port is given")
- port = args.pop(0)
- if args:
- try:
- baudrate = int(args[0])
- except ValueError:
- parser.error("baud rate must be a number, not %r" % args[0])
- args.pop(0)
- if args:
- parser.error("too many arguments")
- else:
- if port is None: port = 0
-
- convert_outgoing = CONVERT_CRLF
- if options.cr:
- convert_outgoing = CONVERT_CR
- elif options.lf:
- convert_outgoing = CONVERT_LF
-
- try:
- miniterm = Miniterm(
- port,
- baudrate,
- options.parity,
- rtscts=options.rtscts,
- xonxoff=options.xonxoff,
- echo=options.echo,
- convert_outgoing=convert_outgoing,
- repr_mode=options.repr_mode,
- )
- except serial.SerialException, e:
- sys.stderr.write("could not open port %r: %s\n" % (port, e))
- sys.exit(1)
-
- if not options.quiet:
- sys.stderr.write('--- Miniterm on %s: %d,%s,%s,%s ---\n' % (
- miniterm.serial.portstr,
- miniterm.serial.baudrate,
- miniterm.serial.bytesize,
- miniterm.serial.parity,
- miniterm.serial.stopbits,
- ))
- sys.stderr.write('--- Quit: %s | Menu: %s | Help: %s followed by %s ---\n' % (
- key_description(EXITCHARCTER),
- key_description(MENUCHARACTER),
- key_description(MENUCHARACTER),
- key_description('\x08'),
- ))
-
- if options.dtr_state is not None:
- if not options.quiet:
- sys.stderr.write('--- forcing DTR %s\n' % (options.dtr_state and 'active' or 'inactive'))
- miniterm.serial.setDTR(options.dtr_state)
- miniterm.dtr_state = options.dtr_state
- if options.rts_state is not None:
- if not options.quiet:
- sys.stderr.write('--- forcing RTS %s\n' % (options.rts_state and 'active' or 'inactive'))
- miniterm.serial.setRTS(options.rts_state)
- miniterm.rts_state = options.rts_state
-
- miniterm.start()
- try:
- miniterm.join(True)
- except KeyboardInterrupt:
- pass
- if not options.quiet:
- sys.stderr.write("\n--- exit ---\n")
- miniterm.join()
-
-
-if __name__ == '__main__':
- main()
diff --git a/python-serial/pyserial/build/lib/serial/urlhandler/__init__.py b/python-serial/pyserial/build/lib/serial/urlhandler/__init__.py
deleted file mode 100644
index e69de29..0000000
diff --git a/python-serial/pyserial/build/lib/serial/urlhandler/protocol_hwgrep.py b/python-serial/pyserial/build/lib/serial/urlhandler/protocol_hwgrep.py
deleted file mode 100644
index 62cda43..0000000
--- a/python-serial/pyserial/build/lib/serial/urlhandler/protocol_hwgrep.py
+++ /dev/null
@@ -1,45 +0,0 @@
-#! python
-#
-# Python Serial Port Extension for Win32, Linux, BSD, Jython
-# see __init__.py
-#
-# This module implements a special URL handler that uses the port listing to
-# find ports by searching the string descriptions.
-#
-# (C) 2011 Chris Liechti
-# this is distributed under a free software license, see license.txt
-#
-# URL format: hwgrep://regexp
-
-import serial
-import serial.tools.list_ports
-
-class Serial(serial.Serial):
- """Just inherit the native Serial port implementation and patch the open function."""
-
- def setPort(self, value):
- """translate port name before storing it"""
- if isinstance(value, basestring) and value.startswith('hwgrep://'):
- serial.Serial.setPort(self, self.fromURL(value))
- else:
- serial.Serial.setPort(self, value)
-
- def fromURL(self, url):
- """extract host and port from an URL string"""
- if url.lower().startswith("hwgrep://"): url = url[9:]
- # use a for loop to get the 1st element from the generator
- for port, desc, hwid in serial.tools.list_ports.grep(url):
- return port
- else:
- raise serial.SerialException('no ports found matching regexp %r' % (url,))
-
- # override property
- port = property(serial.Serial.getPort, setPort, doc="Port setting")
-
-# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-if __name__ == '__main__':
- #~ s = Serial('hwgrep://ttyS0')
- s = Serial(None)
- s.port = 'hwgrep://ttyS0'
- print s
-
diff --git a/python-serial/pyserial/build/lib/serial/urlhandler/protocol_loop.py b/python-serial/pyserial/build/lib/serial/urlhandler/protocol_loop.py
deleted file mode 100644
index e6b3ebd..0000000
--- a/python-serial/pyserial/build/lib/serial/urlhandler/protocol_loop.py
+++ /dev/null
@@ -1,265 +0,0 @@
-#! python
-#
-# Python Serial Port Extension for Win32, Linux, BSD, Jython
-# see __init__.py
-#
-# This module implements a loop back connection receiving itself what it sent.
-#
-# The purpose of this module is.. well... You can run the unit tests with it.
-# and it was so easy to implement ;-)
-#
-# (C) 2001-2011 Chris Liechti
-# this is distributed under a free software license, see license.txt
-#
-# URL format: loop://[option[/option...]]
-# options:
-# - "debug" print diagnostic messages
-
-from serial.serialutil import *
-import threading
-import time
-import logging
-
-# map log level names to constants. used in fromURL()
-LOGGER_LEVELS = {
- 'debug': logging.DEBUG,
- 'info': logging.INFO,
- 'warning': logging.WARNING,
- 'error': logging.ERROR,
- }
-
-
-class LoopbackSerial(SerialBase):
- """Serial port implementation that simulates a loop back connection in plain software."""
-
- BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
- 9600, 19200, 38400, 57600, 115200)
-
- def open(self):
- """Open port with current settings. This may throw a SerialException
- if the port cannot be opened."""
- if self._isOpen:
- raise SerialException("Port is already open.")
- self.logger = None
- self.buffer_lock = threading.Lock()
- self.loop_buffer = bytearray()
- self.cts = False
- self.dsr = False
-
- if self._port is None:
- raise SerialException("Port must be configured before it can be used.")
- # not that there is anything to open, but the function applies the
- # options found in the URL
- self.fromURL(self.port)
-
- # not that there anything to configure...
- self._reconfigurePort()
- # all things set up get, now a clean start
- self._isOpen = True
- if not self._rtscts:
- self.setRTS(True)
- self.setDTR(True)
- self.flushInput()
- self.flushOutput()
-
- def _reconfigurePort(self):
- """Set communication parameters on opened port. for the loop://
- protocol all settings are ignored!"""
- # not that's it of any real use, but it helps in the unit tests
- if not isinstance(self._baudrate, (int, long)) or not 0 < self._baudrate < 2**32:
- raise ValueError("invalid baudrate: %r" % (self._baudrate))
- if self.logger:
- self.logger.info('_reconfigurePort()')
-
- def close(self):
- """Close port"""
- if self._isOpen:
- self._isOpen = False
- # in case of quick reconnects, give the server some time
- time.sleep(0.3)
-
- def makeDeviceName(self, port):
- raise SerialException("there is no sensible way to turn numbers into URLs")
-
- def fromURL(self, url):
- """extract host and port from an URL string"""
- if url.lower().startswith("loop://"): url = url[7:]
- try:
- # process options now, directly altering self
- for option in url.split('/'):
- if '=' in option:
- option, value = option.split('=', 1)
- else:
- value = None
- if not option:
- pass
- elif option == 'logging':
- logging.basicConfig() # XXX is that good to call it here?
- self.logger = logging.getLogger('pySerial.loop')
- self.logger.setLevel(LOGGER_LEVELS[value])
- self.logger.debug('enabled logging')
- else:
- raise ValueError('unknown option: %r' % (option,))
- except ValueError, e:
- raise SerialException('expected a string in the form "[loop://][option[/option...]]": %s' % e)
-
- # - - - - - - - - - - - - - - - - - - - - - - - -
-
- def inWaiting(self):
- """Return the number of characters currently in the input buffer."""
- if not self._isOpen: raise portNotOpenError
- if self.logger:
- # attention the logged value can differ from return value in
- # threaded environments...
- self.logger.debug('inWaiting() -> %d' % (len(self.loop_buffer),))
- return len(self.loop_buffer)
-
- def read(self, size=1):
- """Read size bytes from the serial port. If a timeout is set it may
- return less characters as requested. With no timeout it will block
- until the requested number of bytes is read."""
- if not self._isOpen: raise portNotOpenError
- if self._timeout is not None:
- timeout = time.time() + self._timeout
- else:
- timeout = None
- data = bytearray()
- while size > 0:
- self.buffer_lock.acquire()
- try:
- block = to_bytes(self.loop_buffer[:size])
- del self.loop_buffer[:size]
- finally:
- self.buffer_lock.release()
- data += block
- size -= len(block)
- # check for timeout now, after data has been read.
- # useful for timeout = 0 (non blocking) read
- if timeout and time.time() > timeout:
- break
- return bytes(data)
-
- def write(self, data):
- """Output the given string over the serial port. Can block if the
- connection is blocked. May raise SerialException if the connection is
- closed."""
- if not self._isOpen: raise portNotOpenError
- # ensure we're working with bytes
- data = bytes(data)
- # calculate aprox time that would be used to send the data
- time_used_to_send = 10.0*len(data) / self._baudrate
- # when a write timeout is configured check if we would be successful
- # (not sending anything, not even the part that would have time)
- if self._writeTimeout is not None and time_used_to_send > self._writeTimeout:
- time.sleep(self._writeTimeout) # must wait so that unit test succeeds
- raise writeTimeoutError
- self.buffer_lock.acquire()
- try:
- self.loop_buffer += data
- finally:
- self.buffer_lock.release()
- return len(data)
-
- def flushInput(self):
- """Clear input buffer, discarding all that is in the buffer."""
- if not self._isOpen: raise portNotOpenError
- if self.logger:
- self.logger.info('flushInput()')
- self.buffer_lock.acquire()
- try:
- del self.loop_buffer[:]
- finally:
- self.buffer_lock.release()
-
- def flushOutput(self):
- """Clear output buffer, aborting the current output and
- discarding all that is in the buffer."""
- if not self._isOpen: raise portNotOpenError
- if self.logger:
- self.logger.info('flushOutput()')
-
- def sendBreak(self, duration=0.25):
- """Send break condition. Timed, returns to idle state after given
- duration."""
- if not self._isOpen: raise portNotOpenError
-
- def setBreak(self, level=True):
- """Set break: Controls TXD. When active, to transmitting is
- possible."""
- if not self._isOpen: raise portNotOpenError
- if self.logger:
- self.logger.info('setBreak(%r)' % (level,))
-
- def setRTS(self, level=True):
- """Set terminal status line: Request To Send"""
- if not self._isOpen: raise portNotOpenError
- if self.logger:
- self.logger.info('setRTS(%r) -> state of CTS' % (level,))
- self.cts = level
-
- def setDTR(self, level=True):
- """Set terminal status line: Data Terminal Ready"""
- if not self._isOpen: raise portNotOpenError
- if self.logger:
- self.logger.info('setDTR(%r) -> state of DSR' % (level,))
- self.dsr = level
-
- def getCTS(self):
- """Read terminal status line: Clear To Send"""
- if not self._isOpen: raise portNotOpenError
- if self.logger:
- self.logger.info('getCTS() -> state of RTS (%r)' % (self.cts,))
- return self.cts
-
- def getDSR(self):
- """Read terminal status line: Data Set Ready"""
- if not self._isOpen: raise portNotOpenError
- if self.logger:
- self.logger.info('getDSR() -> state of DTR (%r)' % (self.dsr,))
- return self.dsr
-
- def getRI(self):
- """Read terminal status line: Ring Indicator"""
- if not self._isOpen: raise portNotOpenError
- if self.logger:
- self.logger.info('returning dummy for getRI()')
- return False
-
- def getCD(self):
- """Read terminal status line: Carrier Detect"""
- if not self._isOpen: raise portNotOpenError
- if self.logger:
- self.logger.info('returning dummy for getCD()')
- return True
-
- # - - - platform specific - - -
- # None so far
-
-
-# assemble Serial class with the platform specific implementation and the base
-# for file-like behavior. for Python 2.6 and newer, that provide the new I/O
-# library, derive from io.RawIOBase
-try:
- import io
-except ImportError:
- # classic version with our own file-like emulation
- class Serial(LoopbackSerial, FileLike):
- pass
-else:
- # io library present
- class Serial(LoopbackSerial, io.RawIOBase):
- pass
-
-
-# simple client test
-if __name__ == '__main__':
- import sys
- s = Serial('loop://')
- sys.stdout.write('%s\n' % s)
-
- sys.stdout.write("write...\n")
- s.write("hello\n")
- s.flush()
- sys.stdout.write("read: %s\n" % s.read(5))
-
- s.close()
diff --git a/python-serial/pyserial/build/lib/serial/urlhandler/protocol_rfc2217.py b/python-serial/pyserial/build/lib/serial/urlhandler/protocol_rfc2217.py
deleted file mode 100644
index 981ba45..0000000
--- a/python-serial/pyserial/build/lib/serial/urlhandler/protocol_rfc2217.py
+++ /dev/null
@@ -1,11 +0,0 @@
-#! python
-#
-# Python Serial Port Extension for Win32, Linux, BSD, Jython
-# see ../__init__.py
-#
-# This is a thin wrapper to load the rfc2271 implementation.
-#
-# (C) 2011 Chris Liechti
-# this is distributed under a free software license, see license.txt
-
-from serial.rfc2217 import Serial
diff --git a/python-serial/pyserial/build/lib/serial/urlhandler/protocol_socket.py b/python-serial/pyserial/build/lib/serial/urlhandler/protocol_socket.py
deleted file mode 100644
index ec2e0ab..0000000
--- a/python-serial/pyserial/build/lib/serial/urlhandler/protocol_socket.py
+++ /dev/null
@@ -1,261 +0,0 @@
-#! python
-#
-# Python Serial Port Extension for Win32, Linux, BSD, Jython
-# see __init__.py
-#
-# This module implements a simple socket based client.
-# It does not support changing any port parameters and will silently ignore any
-# requests to do so.
-#
-# The purpose of this module is that applications using pySerial can connect to
-# TCP/IP to serial port converters that do not support RFC 2217.
-#
-# (C) 2001-2011 Chris Liechti
-# this is distributed under a free software license, see license.txt
-#
-# URL format: socket://:[/option[/option...]]
-# options:
-# - "debug" print diagnostic messages
-
-from serial.serialutil import *
-import time
-import socket
-import logging
-
-# map log level names to constants. used in fromURL()
-LOGGER_LEVELS = {
- 'debug': logging.DEBUG,
- 'info': logging.INFO,
- 'warning': logging.WARNING,
- 'error': logging.ERROR,
- }
-
-
-class SocketSerial(SerialBase):
- """Serial port implementation for plain sockets."""
-
- BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
- 9600, 19200, 38400, 57600, 115200)
-
- def open(self):
- """Open port with current settings. This may throw a SerialException
- if the port cannot be opened."""
- self.logger = None
- if self._port is None:
- raise SerialException("Port must be configured before it can be used.")
- if self._isOpen:
- raise SerialException("Port is already open.")
- try:
- self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- self._socket.connect(self.fromURL(self.portstr))
- except Exception, msg:
- self._socket = None
- raise SerialException("Could not open port %s: %s" % (self.portstr, msg))
-
- self._socket.settimeout(2) # used for write timeout support :/
-
- # not that there anything to configure...
- self._reconfigurePort()
- # all things set up get, now a clean start
- self._isOpen = True
- if not self._rtscts:
- self.setRTS(True)
- self.setDTR(True)
- self.flushInput()
- self.flushOutput()
-
- def _reconfigurePort(self):
- """Set communication parameters on opened port. for the socket://
- protocol all settings are ignored!"""
- if self._socket is None:
- raise SerialException("Can only operate on open ports")
- if self.logger:
- self.logger.info('ignored port configuration change')
-
- def close(self):
- """Close port"""
- if self._isOpen:
- if self._socket:
- try:
- self._socket.shutdown(socket.SHUT_RDWR)
- self._socket.close()
- except:
- # ignore errors.
- pass
- self._socket = None
- self._isOpen = False
- # in case of quick reconnects, give the server some time
- time.sleep(0.3)
-
- def makeDeviceName(self, port):
- raise SerialException("there is no sensible way to turn numbers into URLs")
-
- def fromURL(self, url):
- """extract host and port from an URL string"""
- if url.lower().startswith("socket://"): url = url[9:]
- try:
- # is there a "path" (our options)?
- if '/' in url:
- # cut away options
- url, options = url.split('/', 1)
- # process options now, directly altering self
- for option in options.split('/'):
- if '=' in option:
- option, value = option.split('=', 1)
- else:
- value = None
- if option == 'logging':
- logging.basicConfig() # XXX is that good to call it here?
- self.logger = logging.getLogger('pySerial.socket')
- self.logger.setLevel(LOGGER_LEVELS[value])
- self.logger.debug('enabled logging')
- else:
- raise ValueError('unknown option: %r' % (option,))
- # get host and port
- host, port = url.split(':', 1) # may raise ValueError because of unpacking
- port = int(port) # and this if it's not a number
- if not 0 <= port < 65536: raise ValueError("port not in range 0...65535")
- except ValueError, e:
- raise SerialException('expected a string in the form "[rfc2217://]:[/option[/option...]]": %s' % e)
- return (host, port)
-
- # - - - - - - - - - - - - - - - - - - - - - - - -
-
- def inWaiting(self):
- """Return the number of characters currently in the input buffer."""
- if not self._isOpen: raise portNotOpenError
- if self.logger:
- # set this one to debug as the function could be called often...
- self.logger.debug('WARNING: inWaiting returns dummy value')
- return 0 # hmmm, see comment in read()
-
- def read(self, size=1):
- """Read size bytes from the serial port. If a timeout is set it may
- return less characters as requested. With no timeout it will block
- until the requested number of bytes is read."""
- if not self._isOpen: raise portNotOpenError
- data = bytearray()
- timeout = time.time() + self._timeout
- while len(data) < size and time.time() < timeout:
- try:
- # an implementation with internal buffer would be better
- # performing...
- data = self._socket.recv(size - len(data))
- except socket.timeout:
- # just need to get out of recv form time to time to check if
- # still alive
- continue
- except socket.error, e:
- # connection fails -> terminate loop
- raise SerialException('connection failed (%s)' % e)
- return bytes(data)
-
- def write(self, data):
- """Output the given string over the serial port. Can block if the
- connection is blocked. May raise SerialException if the connection is
- closed."""
- if not self._isOpen: raise portNotOpenError
- try:
- self._socket.sendall(data)
- except socket.error, e:
- raise SerialException("socket connection failed: %s" % e) # XXX what exception if socket connection fails
- return len(data)
-
- def flushInput(self):
- """Clear input buffer, discarding all that is in the buffer."""
- if not self._isOpen: raise portNotOpenError
- if self.logger:
- self.logger.info('ignored flushInput')
-
- def flushOutput(self):
- """Clear output buffer, aborting the current output and
- discarding all that is in the buffer."""
- if not self._isOpen: raise portNotOpenError
- if self.logger:
- self.logger.info('ignored flushOutput')
-
- def sendBreak(self, duration=0.25):
- """Send break condition. Timed, returns to idle state after given
- duration."""
- if not self._isOpen: raise portNotOpenError
- if self.logger:
- self.logger.info('ignored sendBreak(%r)' % (duration,))
-
- def setBreak(self, level=True):
- """Set break: Controls TXD. When active, to transmitting is
- possible."""
- if not self._isOpen: raise portNotOpenError
- if self.logger:
- self.logger.info('ignored setBreak(%r)' % (level,))
-
- def setRTS(self, level=True):
- """Set terminal status line: Request To Send"""
- if not self._isOpen: raise portNotOpenError
- if self.logger:
- self.logger.info('ignored setRTS(%r)' % (level,))
-
- def setDTR(self, level=True):
- """Set terminal status line: Data Terminal Ready"""
- if not self._isOpen: raise portNotOpenError
- if self.logger:
- self.logger.info('ignored setDTR(%r)' % (level,))
-
- def getCTS(self):
- """Read terminal status line: Clear To Send"""
- if not self._isOpen: raise portNotOpenError
- if self.logger:
- self.logger.info('returning dummy for getCTS()')
- return True
-
- def getDSR(self):
- """Read terminal status line: Data Set Ready"""
- if not self._isOpen: raise portNotOpenError
- if self.logger:
- self.logger.info('returning dummy for getDSR()')
- return True
-
- def getRI(self):
- """Read terminal status line: Ring Indicator"""
- if not self._isOpen: raise portNotOpenError
- if self.logger:
- self.logger.info('returning dummy for getRI()')
- return False
-
- def getCD(self):
- """Read terminal status line: Carrier Detect"""
- if not self._isOpen: raise portNotOpenError
- if self.logger:
- self.logger.info('returning dummy for getCD()')
- return True
-
- # - - - platform specific - - -
- # None so far
-
-
-# assemble Serial class with the platform specific implementation and the base
-# for file-like behavior. for Python 2.6 and newer, that provide the new I/O
-# library, derive from io.RawIOBase
-try:
- import io
-except ImportError:
- # classic version with our own file-like emulation
- class Serial(SocketSerial, FileLike):
- pass
-else:
- # io library present
- class Serial(SocketSerial, io.RawIOBase):
- pass
-
-
-# simple client test
-if __name__ == '__main__':
- import sys
- s = Serial('socket://localhost:7000')
- sys.stdout.write('%s\n' % s)
-
- sys.stdout.write("write...\n")
- s.write("hello\n")
- s.flush()
- sys.stdout.write("read: %s\n" % s.read(5))
-
- s.close()
diff --git a/python-serial/pyserial/build/lib/serial/win32.py b/python-serial/pyserial/build/lib/serial/win32.py
deleted file mode 100644
index 61b3d7a..0000000
--- a/python-serial/pyserial/build/lib/serial/win32.py
+++ /dev/null
@@ -1,320 +0,0 @@
-from ctypes import *
-from ctypes.wintypes import HANDLE
-from ctypes.wintypes import BOOL
-from ctypes.wintypes import LPCWSTR
-_stdcall_libraries = {}
-_stdcall_libraries['kernel32'] = WinDLL('kernel32')
-from ctypes.wintypes import DWORD
-from ctypes.wintypes import WORD
-from ctypes.wintypes import BYTE
-
-INVALID_HANDLE_VALUE = HANDLE(-1).value
-
-# some details of the windows API differ between 32 and 64 bit systems..
-def is_64bit():
- """Returns true when running on a 64 bit system"""
- return sizeof(c_ulong) != sizeof(c_void_p)
-
-# ULONG_PTR is a an ordinary number, not a pointer and contrary to the name it
-# is either 32 or 64 bits, depending on the type of windows...
-# so test if this a 32 bit windows...
-if is_64bit():
- # assume 64 bits
- ULONG_PTR = c_int64
-else:
- # 32 bits
- ULONG_PTR = c_ulong
-
-
-class _SECURITY_ATTRIBUTES(Structure):
- pass
-LPSECURITY_ATTRIBUTES = POINTER(_SECURITY_ATTRIBUTES)
-
-
-try:
- CreateEventW = _stdcall_libraries['kernel32'].CreateEventW
-except AttributeError:
- # Fallback to non wide char version for old OS...
- from ctypes.wintypes import LPCSTR
- CreateEventA = _stdcall_libraries['kernel32'].CreateEventA
- CreateEventA.restype = HANDLE
- CreateEventA.argtypes = [LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCSTR]
- CreateEvent=CreateEventA
-
- CreateFileA = _stdcall_libraries['kernel32'].CreateFileA
- CreateFileA.restype = HANDLE
- CreateFileA.argtypes = [LPCSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE]
- CreateFile = CreateFileA
-else:
- CreateEventW.restype = HANDLE
- CreateEventW.argtypes = [LPSECURITY_ATTRIBUTES, BOOL, BOOL, LPCWSTR]
- CreateEvent = CreateEventW # alias
-
- CreateFileW = _stdcall_libraries['kernel32'].CreateFileW
- CreateFileW.restype = HANDLE
- CreateFileW.argtypes = [LPCWSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE]
- CreateFile = CreateFileW # alias
-
-class _OVERLAPPED(Structure):
- pass
-OVERLAPPED = _OVERLAPPED
-
-class _COMSTAT(Structure):
- pass
-COMSTAT = _COMSTAT
-
-class _DCB(Structure):
- pass
-DCB = _DCB
-
-class _COMMTIMEOUTS(Structure):
- pass
-COMMTIMEOUTS = _COMMTIMEOUTS
-
-GetLastError = _stdcall_libraries['kernel32'].GetLastError
-GetLastError.restype = DWORD
-GetLastError.argtypes = []
-
-LPOVERLAPPED = POINTER(_OVERLAPPED)
-LPDWORD = POINTER(DWORD)
-
-GetOverlappedResult = _stdcall_libraries['kernel32'].GetOverlappedResult
-GetOverlappedResult.restype = BOOL
-GetOverlappedResult.argtypes = [HANDLE, LPOVERLAPPED, LPDWORD, BOOL]
-
-ResetEvent = _stdcall_libraries['kernel32'].ResetEvent
-ResetEvent.restype = BOOL
-ResetEvent.argtypes = [HANDLE]
-
-LPCVOID = c_void_p
-
-WriteFile = _stdcall_libraries['kernel32'].WriteFile
-WriteFile.restype = BOOL
-WriteFile.argtypes = [HANDLE, LPCVOID, DWORD, LPDWORD, LPOVERLAPPED]
-
-LPVOID = c_void_p
-
-ReadFile = _stdcall_libraries['kernel32'].ReadFile
-ReadFile.restype = BOOL
-ReadFile.argtypes = [HANDLE, LPVOID, DWORD, LPDWORD, LPOVERLAPPED]
-
-CloseHandle = _stdcall_libraries['kernel32'].CloseHandle
-CloseHandle.restype = BOOL
-CloseHandle.argtypes = [HANDLE]
-
-ClearCommBreak = _stdcall_libraries['kernel32'].ClearCommBreak
-ClearCommBreak.restype = BOOL
-ClearCommBreak.argtypes = [HANDLE]
-
-LPCOMSTAT = POINTER(_COMSTAT)
-
-ClearCommError = _stdcall_libraries['kernel32'].ClearCommError
-ClearCommError.restype = BOOL
-ClearCommError.argtypes = [HANDLE, LPDWORD, LPCOMSTAT]
-
-SetupComm = _stdcall_libraries['kernel32'].SetupComm
-SetupComm.restype = BOOL
-SetupComm.argtypes = [HANDLE, DWORD, DWORD]
-
-EscapeCommFunction = _stdcall_libraries['kernel32'].EscapeCommFunction
-EscapeCommFunction.restype = BOOL
-EscapeCommFunction.argtypes = [HANDLE, DWORD]
-
-GetCommModemStatus = _stdcall_libraries['kernel32'].GetCommModemStatus
-GetCommModemStatus.restype = BOOL
-GetCommModemStatus.argtypes = [HANDLE, LPDWORD]
-
-LPDCB = POINTER(_DCB)
-
-GetCommState = _stdcall_libraries['kernel32'].GetCommState
-GetCommState.restype = BOOL
-GetCommState.argtypes = [HANDLE, LPDCB]
-
-LPCOMMTIMEOUTS = POINTER(_COMMTIMEOUTS)
-
-GetCommTimeouts = _stdcall_libraries['kernel32'].GetCommTimeouts
-GetCommTimeouts.restype = BOOL
-GetCommTimeouts.argtypes = [HANDLE, LPCOMMTIMEOUTS]
-
-PurgeComm = _stdcall_libraries['kernel32'].PurgeComm
-PurgeComm.restype = BOOL
-PurgeComm.argtypes = [HANDLE, DWORD]
-
-SetCommBreak = _stdcall_libraries['kernel32'].SetCommBreak
-SetCommBreak.restype = BOOL
-SetCommBreak.argtypes = [HANDLE]
-
-SetCommMask = _stdcall_libraries['kernel32'].SetCommMask
-SetCommMask.restype = BOOL
-SetCommMask.argtypes = [HANDLE, DWORD]
-
-SetCommState = _stdcall_libraries['kernel32'].SetCommState
-SetCommState.restype = BOOL
-SetCommState.argtypes = [HANDLE, LPDCB]
-
-SetCommTimeouts = _stdcall_libraries['kernel32'].SetCommTimeouts
-SetCommTimeouts.restype = BOOL
-SetCommTimeouts.argtypes = [HANDLE, LPCOMMTIMEOUTS]
-
-WaitForSingleObject = _stdcall_libraries['kernel32'].WaitForSingleObject
-WaitForSingleObject.restype = DWORD
-WaitForSingleObject.argtypes = [HANDLE, DWORD]
-
-ONESTOPBIT = 0 # Variable c_int
-TWOSTOPBITS = 2 # Variable c_int
-ONE5STOPBITS = 1
-
-NOPARITY = 0 # Variable c_int
-ODDPARITY = 1 # Variable c_int
-EVENPARITY = 2 # Variable c_int
-MARKPARITY = 3
-SPACEPARITY = 4
-
-RTS_CONTROL_HANDSHAKE = 2 # Variable c_int
-RTS_CONTROL_DISABLE = 0 # Variable c_int
-RTS_CONTROL_ENABLE = 1 # Variable c_int
-RTS_CONTROL_TOGGLE = 3 # Variable c_int
-SETRTS = 3
-CLRRTS = 4
-
-DTR_CONTROL_HANDSHAKE = 2 # Variable c_int
-DTR_CONTROL_DISABLE = 0 # Variable c_int
-DTR_CONTROL_ENABLE = 1 # Variable c_int
-SETDTR = 5
-CLRDTR = 6
-
-MS_DSR_ON = 32 # Variable c_ulong
-EV_RING = 256 # Variable c_int
-EV_PERR = 512 # Variable c_int
-EV_ERR = 128 # Variable c_int
-SETXOFF = 1 # Variable c_int
-EV_RXCHAR = 1 # Variable c_int
-GENERIC_WRITE = 1073741824 # Variable c_long
-PURGE_TXCLEAR = 4 # Variable c_int
-FILE_FLAG_OVERLAPPED = 1073741824 # Variable c_int
-EV_DSR = 16 # Variable c_int
-MAXDWORD = 4294967295L # Variable c_uint
-EV_RLSD = 32 # Variable c_int
-ERROR_IO_PENDING = 997 # Variable c_long
-MS_CTS_ON = 16 # Variable c_ulong
-EV_EVENT1 = 2048 # Variable c_int
-EV_RX80FULL = 1024 # Variable c_int
-PURGE_RXABORT = 2 # Variable c_int
-FILE_ATTRIBUTE_NORMAL = 128 # Variable c_int
-PURGE_TXABORT = 1 # Variable c_int
-SETXON = 2 # Variable c_int
-OPEN_EXISTING = 3 # Variable c_int
-MS_RING_ON = 64 # Variable c_ulong
-EV_TXEMPTY = 4 # Variable c_int
-EV_RXFLAG = 2 # Variable c_int
-MS_RLSD_ON = 128 # Variable c_ulong
-GENERIC_READ = 2147483648L # Variable c_ulong
-EV_EVENT2 = 4096 # Variable c_int
-EV_CTS = 8 # Variable c_int
-EV_BREAK = 64 # Variable c_int
-PURGE_RXCLEAR = 8 # Variable c_int
-INFINITE = 0xFFFFFFFFL
-
-
-class N11_OVERLAPPED4DOLLAR_48E(Union):
- pass
-class N11_OVERLAPPED4DOLLAR_484DOLLAR_49E(Structure):
- pass
-N11_OVERLAPPED4DOLLAR_484DOLLAR_49E._fields_ = [
- ('Offset', DWORD),
- ('OffsetHigh', DWORD),
-]
-
-PVOID = c_void_p
-
-N11_OVERLAPPED4DOLLAR_48E._anonymous_ = ['_0']
-N11_OVERLAPPED4DOLLAR_48E._fields_ = [
- ('_0', N11_OVERLAPPED4DOLLAR_484DOLLAR_49E),
- ('Pointer', PVOID),
-]
-_OVERLAPPED._anonymous_ = ['_0']
-_OVERLAPPED._fields_ = [
- ('Internal', ULONG_PTR),
- ('InternalHigh', ULONG_PTR),
- ('_0', N11_OVERLAPPED4DOLLAR_48E),
- ('hEvent', HANDLE),
-]
-_SECURITY_ATTRIBUTES._fields_ = [
- ('nLength', DWORD),
- ('lpSecurityDescriptor', LPVOID),
- ('bInheritHandle', BOOL),
-]
-_COMSTAT._fields_ = [
- ('fCtsHold', DWORD, 1),
- ('fDsrHold', DWORD, 1),
- ('fRlsdHold', DWORD, 1),
- ('fXoffHold', DWORD, 1),
- ('fXoffSent', DWORD, 1),
- ('fEof', DWORD, 1),
- ('fTxim', DWORD, 1),
- ('fReserved', DWORD, 25),
- ('cbInQue', DWORD),
- ('cbOutQue', DWORD),
-]
-_DCB._fields_ = [
- ('DCBlength', DWORD),
- ('BaudRate', DWORD),
- ('fBinary', DWORD, 1),
- ('fParity', DWORD, 1),
- ('fOutxCtsFlow', DWORD, 1),
- ('fOutxDsrFlow', DWORD, 1),
- ('fDtrControl', DWORD, 2),
- ('fDsrSensitivity', DWORD, 1),
- ('fTXContinueOnXoff', DWORD, 1),
- ('fOutX', DWORD, 1),
- ('fInX', DWORD, 1),
- ('fErrorChar', DWORD, 1),
- ('fNull', DWORD, 1),
- ('fRtsControl', DWORD, 2),
- ('fAbortOnError', DWORD, 1),
- ('fDummy2', DWORD, 17),
- ('wReserved', WORD),
- ('XonLim', WORD),
- ('XoffLim', WORD),
- ('ByteSize', BYTE),
- ('Parity', BYTE),
- ('StopBits', BYTE),
- ('XonChar', c_char),
- ('XoffChar', c_char),
- ('ErrorChar', c_char),
- ('EofChar', c_char),
- ('EvtChar', c_char),
- ('wReserved1', WORD),
-]
-_COMMTIMEOUTS._fields_ = [
- ('ReadIntervalTimeout', DWORD),
- ('ReadTotalTimeoutMultiplier', DWORD),
- ('ReadTotalTimeoutConstant', DWORD),
- ('WriteTotalTimeoutMultiplier', DWORD),
- ('WriteTotalTimeoutConstant', DWORD),
-]
-__all__ = ['GetLastError', 'MS_CTS_ON', 'FILE_ATTRIBUTE_NORMAL',
- 'DTR_CONTROL_ENABLE', '_COMSTAT', 'MS_RLSD_ON',
- 'GetOverlappedResult', 'SETXON', 'PURGE_TXABORT',
- 'PurgeComm', 'N11_OVERLAPPED4DOLLAR_48E', 'EV_RING',
- 'ONESTOPBIT', 'SETXOFF', 'PURGE_RXABORT', 'GetCommState',
- 'RTS_CONTROL_ENABLE', '_DCB', 'CreateEvent',
- '_COMMTIMEOUTS', '_SECURITY_ATTRIBUTES', 'EV_DSR',
- 'EV_PERR', 'EV_RXFLAG', 'OPEN_EXISTING', 'DCB',
- 'FILE_FLAG_OVERLAPPED', 'EV_CTS', 'SetupComm',
- 'LPOVERLAPPED', 'EV_TXEMPTY', 'ClearCommBreak',
- 'LPSECURITY_ATTRIBUTES', 'SetCommBreak', 'SetCommTimeouts',
- 'COMMTIMEOUTS', 'ODDPARITY', 'EV_RLSD',
- 'GetCommModemStatus', 'EV_EVENT2', 'PURGE_TXCLEAR',
- 'EV_BREAK', 'EVENPARITY', 'LPCVOID', 'COMSTAT', 'ReadFile',
- 'PVOID', '_OVERLAPPED', 'WriteFile', 'GetCommTimeouts',
- 'ResetEvent', 'EV_RXCHAR', 'LPCOMSTAT', 'ClearCommError',
- 'ERROR_IO_PENDING', 'EscapeCommFunction', 'GENERIC_READ',
- 'RTS_CONTROL_HANDSHAKE', 'OVERLAPPED',
- 'DTR_CONTROL_HANDSHAKE', 'PURGE_RXCLEAR', 'GENERIC_WRITE',
- 'LPDCB', 'CreateEventW', 'SetCommMask', 'EV_EVENT1',
- 'SetCommState', 'LPVOID', 'CreateFileW', 'LPDWORD',
- 'EV_RX80FULL', 'TWOSTOPBITS', 'LPCOMMTIMEOUTS', 'MAXDWORD',
- 'MS_DSR_ON', 'MS_RING_ON',
- 'N11_OVERLAPPED4DOLLAR_484DOLLAR_49E', 'EV_ERR',
- 'ULONG_PTR', 'CreateFile', 'NOPARITY', 'CloseHandle']
diff --git a/python-serial/pyserial/build/scripts-2.6/miniterm.py b/python-serial/pyserial/build/scripts-2.6/miniterm.py
deleted file mode 100644
index dda2c4d..0000000
--- a/python-serial/pyserial/build/scripts-2.6/miniterm.py
+++ /dev/null
@@ -1,645 +0,0 @@
-#!C:\depot_tools\python_bin\python.exe
-
-# Very simple serial terminal
-# (C)2002-2011 Chris Liechti
-
-# Input characters are sent directly (only LF -> CR/LF/CRLF translation is
-# done), received characters are displayed as is (or escaped trough pythons
-# repr, useful for debug purposes)
-
-
-import sys, os, serial, threading
-
-EXITCHARCTER = '\x1d' # GS/CTRL+]
-MENUCHARACTER = '\x14' # Menu: CTRL+T
-
-
-def key_description(character):
- """generate a readable description for a key"""
- ascii_code = ord(character)
- if ascii_code < 32:
- return 'Ctrl+%c' % (ord('@') + ascii_code)
- else:
- return repr(character)
-
-
-# help text, starts with blank line! it's a function so that the current values
-# for the shortcut keys is used and not the value at program start
-def get_help_text():
- return """
---- pySerial (%(version)s) - miniterm - help
----
---- %(exit)-8s Exit program
---- %(menu)-8s Menu escape key, followed by:
---- Menu keys:
---- %(itself)-7s Send the menu character itself to remote
---- %(exchar)-7s Send the exit character itself to remote
---- %(info)-7s Show info
---- %(upload)-7s Upload file (prompt will be shown)
---- Toggles:
---- %(rts)-7s RTS %(echo)-7s local echo
---- %(dtr)-7s DTR %(break)-7s BREAK
---- %(lfm)-7s line feed %(repr)-7s Cycle repr mode
----
---- Port settings (%(menu)s followed by the following):
---- p change port
---- 7 8 set data bits
---- n e o s m change parity (None, Even, Odd, Space, Mark)
---- 1 2 3 set stop bits (1, 2, 1.5)
---- b change baud rate
---- x X disable/enable software flow control
---- r R disable/enable hardware flow control
-""" % {
- 'version': getattr(serial, 'VERSION', 'unknown version'),
- 'exit': key_description(EXITCHARCTER),
- 'menu': key_description(MENUCHARACTER),
- 'rts': key_description('\x12'),
- 'repr': key_description('\x01'),
- 'dtr': key_description('\x04'),
- 'lfm': key_description('\x0c'),
- 'break': key_description('\x02'),
- 'echo': key_description('\x05'),
- 'info': key_description('\x09'),
- 'upload': key_description('\x15'),
- 'itself': key_description(MENUCHARACTER),
- 'exchar': key_description(EXITCHARCTER),
-}
-
-if sys.version_info >= (3, 0):
- def character(b):
- return b.decode('latin1')
-else:
- def character(b):
- return b
-
-# first choose a platform dependant way to read single characters from the console
-global console
-
-if os.name == 'nt':
- import msvcrt
- class Console(object):
- def __init__(self):
- pass
-
- def setup(self):
- pass # Do nothing for 'nt'
-
- def cleanup(self):
- pass # Do nothing for 'nt'
-
- def getkey(self):
- while True:
- z = msvcrt.getch()
- if z == '\0' or z == '\xe0': # functions keys, ignore
- msvcrt.getch()
- else:
- if z == '\r':
- return '\n'
- return z
-
- console = Console()
-
-elif os.name == 'posix':
- import termios, sys, os
- class Console(object):
- def __init__(self):
- self.fd = sys.stdin.fileno()
-
- def setup(self):
- self.old = termios.tcgetattr(self.fd)
- new = termios.tcgetattr(self.fd)
- new[3] = new[3] & ~termios.ICANON & ~termios.ECHO & ~termios.ISIG
- new[6][termios.VMIN] = 1
- new[6][termios.VTIME] = 0
- termios.tcsetattr(self.fd, termios.TCSANOW, new)
-
- def getkey(self):
- c = os.read(self.fd, 1)
- return c
-
- def cleanup(self):
- termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old)
-
- console = Console()
-
- def cleanup_console():
- console.cleanup()
-
- console.setup()
- sys.exitfunc = cleanup_console # terminal modes have to be restored on exit...
-
-else:
- raise NotImplementedError("Sorry no implementation for your platform (%s) available." % sys.platform)
-
-
-CONVERT_CRLF = 2
-CONVERT_CR = 1
-CONVERT_LF = 0
-NEWLINE_CONVERISON_MAP = ('\n', '\r', '\r\n')
-LF_MODES = ('LF', 'CR', 'CR/LF')
-
-REPR_MODES = ('raw', 'some control', 'all control', 'hex')
-
-class Miniterm(object):
- def __init__(self, port, baudrate, parity, rtscts, xonxoff, echo=False, convert_outgoing=CONVERT_CRLF, repr_mode=0):
- try:
- self.serial = serial.serial_for_url(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1)
- except AttributeError:
- # happens when the installed pyserial is older than 2.5. use the
- # Serial class directly then.
- self.serial = serial.Serial(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=1)
- self.echo = echo
- self.repr_mode = repr_mode
- self.convert_outgoing = convert_outgoing
- self.newline = NEWLINE_CONVERISON_MAP[self.convert_outgoing]
- self.dtr_state = True
- self.rts_state = True
- self.break_state = False
-
- def _start_reader(self):
- """Start reader thread"""
- self._reader_alive = True
- # start serial->console thread
- self.receiver_thread = threading.Thread(target=self.reader)
- self.receiver_thread.setDaemon(True)
- self.receiver_thread.start()
-
- def _stop_reader(self):
- """Stop reader thread only, wait for clean exit of thread"""
- self._reader_alive = False
- self.receiver_thread.join()
-
-
- def start(self):
- self.alive = True
- self._start_reader()
- # enter console->serial loop
- self.transmitter_thread = threading.Thread(target=self.writer)
- self.transmitter_thread.setDaemon(True)
- self.transmitter_thread.start()
-
- def stop(self):
- self.alive = False
-
- def join(self, transmit_only=False):
- self.transmitter_thread.join()
- if not transmit_only:
- self.receiver_thread.join()
-
- def dump_port_settings(self):
- sys.stderr.write("\n--- Settings: %s %s,%s,%s,%s\n" % (
- self.serial.portstr,
- self.serial.baudrate,
- self.serial.bytesize,
- self.serial.parity,
- self.serial.stopbits))
- sys.stderr.write('--- RTS: %-8s DTR: %-8s BREAK: %-8s\n' % (
- (self.rts_state and 'active' or 'inactive'),
- (self.dtr_state and 'active' or 'inactive'),
- (self.break_state and 'active' or 'inactive')))
- try:
- sys.stderr.write('--- CTS: %-8s DSR: %-8s RI: %-8s CD: %-8s\n' % (
- (self.serial.getCTS() and 'active' or 'inactive'),
- (self.serial.getDSR() and 'active' or 'inactive'),
- (self.serial.getRI() and 'active' or 'inactive'),
- (self.serial.getCD() and 'active' or 'inactive')))
- except serial.SerialException:
- # on RFC 2217 ports it can happen to no modem state notification was
- # yet received. ignore this error.
- pass
- sys.stderr.write('--- software flow control: %s\n' % (self.serial.xonxoff and 'active' or 'inactive'))
- sys.stderr.write('--- hardware flow control: %s\n' % (self.serial.rtscts and 'active' or 'inactive'))
- sys.stderr.write('--- data escaping: %s linefeed: %s\n' % (
- REPR_MODES[self.repr_mode],
- LF_MODES[self.convert_outgoing]))
-
- def reader(self):
- """loop and copy serial->console"""
- try:
- while self.alive and self._reader_alive:
- data = character(self.serial.read(1))
-
- if self.repr_mode == 0:
- # direct output, just have to care about newline setting
- if data == '\r' and self.convert_outgoing == CONVERT_CR:
- sys.stdout.write('\n')
- else:
- sys.stdout.write(data)
- elif self.repr_mode == 1:
- # escape non-printable, let pass newlines
- if self.convert_outgoing == CONVERT_CRLF and data in '\r\n':
- if data == '\n':
- sys.stdout.write('\n')
- elif data == '\r':
- pass
- elif data == '\n' and self.convert_outgoing == CONVERT_LF:
- sys.stdout.write('\n')
- elif data == '\r' and self.convert_outgoing == CONVERT_CR:
- sys.stdout.write('\n')
- else:
- sys.stdout.write(repr(data)[1:-1])
- elif self.repr_mode == 2:
- # escape all non-printable, including newline
- sys.stdout.write(repr(data)[1:-1])
- elif self.repr_mode == 3:
- # escape everything (hexdump)
- for c in data:
- sys.stdout.write("%s " % c.encode('hex'))
- sys.stdout.flush()
- except serial.SerialException, e:
- self.alive = False
- # would be nice if the console reader could be interruptted at this
- # point...
- raise
-
-
- def writer(self):
- """\
- Loop and copy console->serial until EXITCHARCTER character is
- found. When MENUCHARACTER is found, interpret the next key
- locally.
- """
- menu_active = False
- try:
- while self.alive:
- try:
- b = console.getkey()
- except KeyboardInterrupt:
- b = serial.to_bytes([3])
- c = character(b)
- if menu_active:
- if c == MENUCHARACTER or c == EXITCHARCTER: # Menu character again/exit char -> send itself
- self.serial.write(b) # send character
- if self.echo:
- sys.stdout.write(c)
- elif c == '\x15': # CTRL+U -> upload file
- sys.stderr.write('\n--- File to upload: ')
- sys.stderr.flush()
- console.cleanup()
- filename = sys.stdin.readline().rstrip('\r\n')
- if filename:
- try:
- file = open(filename, 'r')
- sys.stderr.write('--- Sending file %s ---\n' % filename)
- while True:
- line = file.readline().rstrip('\r\n')
- if not line:
- break
- self.serial.write(line)
- self.serial.write('\r\n')
- # Wait for output buffer to drain.
- self.serial.flush()
- sys.stderr.write('.') # Progress indicator.
- sys.stderr.write('\n--- File %s sent ---\n' % filename)
- except IOError, e:
- sys.stderr.write('--- ERROR opening file %s: %s ---\n' % (filename, e))
- console.setup()
- elif c in '\x08hH?': # CTRL+H, h, H, ? -> Show help
- sys.stderr.write(get_help_text())
- elif c == '\x12': # CTRL+R -> Toggle RTS
- self.rts_state = not self.rts_state
- self.serial.setRTS(self.rts_state)
- sys.stderr.write('--- RTS %s ---\n' % (self.rts_state and 'active' or 'inactive'))
- elif c == '\x04': # CTRL+D -> Toggle DTR
- self.dtr_state = not self.dtr_state
- self.serial.setDTR(self.dtr_state)
- sys.stderr.write('--- DTR %s ---\n' % (self.dtr_state and 'active' or 'inactive'))
- elif c == '\x02': # CTRL+B -> toggle BREAK condition
- self.break_state = not self.break_state
- self.serial.setBreak(self.break_state)
- sys.stderr.write('--- BREAK %s ---\n' % (self.break_state and 'active' or 'inactive'))
- elif c == '\x05': # CTRL+E -> toggle local echo
- self.echo = not self.echo
- sys.stderr.write('--- local echo %s ---\n' % (self.echo and 'active' or 'inactive'))
- elif c == '\x09': # CTRL+I -> info
- self.dump_port_settings()
- elif c == '\x01': # CTRL+A -> cycle escape mode
- self.repr_mode += 1
- if self.repr_mode > 3:
- self.repr_mode = 0
- sys.stderr.write('--- escape data: %s ---\n' % (
- REPR_MODES[self.repr_mode],
- ))
- elif c == '\x0c': # CTRL+L -> cycle linefeed mode
- self.convert_outgoing += 1
- if self.convert_outgoing > 2:
- self.convert_outgoing = 0
- self.newline = NEWLINE_CONVERISON_MAP[self.convert_outgoing]
- sys.stderr.write('--- line feed %s ---\n' % (
- LF_MODES[self.convert_outgoing],
- ))
- elif c in 'pP': # P -> change port
- sys.stderr.write('\n--- Enter port name: ')
- sys.stderr.flush()
- console.cleanup()
- try:
- port = sys.stdin.readline().strip()
- except KeyboardInterrupt:
- port = None
- console.setup()
- if port and port != self.serial.port:
- # reader thread needs to be shut down
- self._stop_reader()
- # save settings
- settings = self.serial.getSettingsDict()
- try:
- try:
- new_serial = serial.serial_for_url(port, do_not_open=True)
- except AttributeError:
- # happens when the installed pyserial is older than 2.5. use the
- # Serial class directly then.
- new_serial = serial.Serial()
- new_serial.port = port
- # restore settings and open
- new_serial.applySettingsDict(settings)
- new_serial.open()
- new_serial.setRTS(self.rts_state)
- new_serial.setDTR(self.dtr_state)
- new_serial.setBreak(self.break_state)
- except Exception, e:
- sys.stderr.write('--- ERROR opening new port: %s ---\n' % (e,))
- new_serial.close()
- else:
- self.serial.close()
- self.serial = new_serial
- sys.stderr.write('--- Port changed to: %s ---\n' % (self.serial.port,))
- # and restart the reader thread
- self._start_reader()
- elif c in 'bB': # B -> change baudrate
- sys.stderr.write('\n--- Baudrate: ')
- sys.stderr.flush()
- console.cleanup()
- backup = self.serial.baudrate
- try:
- self.serial.baudrate = int(sys.stdin.readline().strip())
- except ValueError, e:
- sys.stderr.write('--- ERROR setting baudrate: %s ---\n' % (e,))
- self.serial.baudrate = backup
- else:
- self.dump_port_settings()
- console.setup()
- elif c == '8': # 8 -> change to 8 bits
- self.serial.bytesize = serial.EIGHTBITS
- self.dump_port_settings()
- elif c == '7': # 7 -> change to 8 bits
- self.serial.bytesize = serial.SEVENBITS
- self.dump_port_settings()
- elif c in 'eE': # E -> change to even parity
- self.serial.parity = serial.PARITY_EVEN
- self.dump_port_settings()
- elif c in 'oO': # O -> change to odd parity
- self.serial.parity = serial.PARITY_ODD
- self.dump_port_settings()
- elif c in 'mM': # M -> change to mark parity
- self.serial.parity = serial.PARITY_MARK
- self.dump_port_settings()
- elif c in 'sS': # S -> change to space parity
- self.serial.parity = serial.PARITY_SPACE
- self.dump_port_settings()
- elif c in 'nN': # N -> change to no parity
- self.serial.parity = serial.PARITY_NONE
- self.dump_port_settings()
- elif c == '1': # 1 -> change to 1 stop bits
- self.serial.stopbits = serial.STOPBITS_ONE
- self.dump_port_settings()
- elif c == '2': # 2 -> change to 2 stop bits
- self.serial.stopbits = serial.STOPBITS_TWO
- self.dump_port_settings()
- elif c == '3': # 3 -> change to 1.5 stop bits
- self.serial.stopbits = serial.STOPBITS_ONE_POINT_FIVE
- self.dump_port_settings()
- elif c in 'xX': # X -> change software flow control
- self.serial.xonxoff = (c == 'X')
- self.dump_port_settings()
- elif c in 'rR': # R -> change hardware flow control
- self.serial.rtscts = (c == 'R')
- self.dump_port_settings()
- else:
- sys.stderr.write('--- unknown menu character %s --\n' % key_description(c))
- menu_active = False
- elif c == MENUCHARACTER: # next char will be for menu
- menu_active = True
- elif c == EXITCHARCTER:
- self.stop()
- break # exit app
- elif c == '\n':
- self.serial.write(self.newline) # send newline character(s)
- if self.echo:
- sys.stdout.write(c) # local echo is a real newline in any case
- sys.stdout.flush()
- else:
- self.serial.write(b) # send byte
- if self.echo:
- sys.stdout.write(c)
- sys.stdout.flush()
- except:
- self.alive = False
- raise
-
-def main():
- import optparse
-
- parser = optparse.OptionParser(
- usage = "%prog [options] [port [baudrate]]",
- description = "Miniterm - A simple terminal program for the serial port."
- )
-
- parser.add_option("-p", "--port",
- dest = "port",
- help = "port, a number or a device name. (deprecated option, use parameter instead)",
- default = None
- )
-
- parser.add_option("-b", "--baud",
- dest = "baudrate",
- action = "store",
- type = 'int',
- help = "set baud rate, default %default",
- default = 9600
- )
-
- parser.add_option("--parity",
- dest = "parity",
- action = "store",
- help = "set parity, one of [N, E, O, S, M], default=N",
- default = 'N'
- )
-
- parser.add_option("-e", "--echo",
- dest = "echo",
- action = "store_true",
- help = "enable local echo (default off)",
- default = False
- )
-
- parser.add_option("--rtscts",
- dest = "rtscts",
- action = "store_true",
- help = "enable RTS/CTS flow control (default off)",
- default = False
- )
-
- parser.add_option("--xonxoff",
- dest = "xonxoff",
- action = "store_true",
- help = "enable software flow control (default off)",
- default = False
- )
-
- parser.add_option("--cr",
- dest = "cr",
- action = "store_true",
- help = "do not send CR+LF, send CR only",
- default = False
- )
-
- parser.add_option("--lf",
- dest = "lf",
- action = "store_true",
- help = "do not send CR+LF, send LF only",
- default = False
- )
-
- parser.add_option("-D", "--debug",
- dest = "repr_mode",
- action = "count",
- help = """debug received data (escape non-printable chars)
---debug can be given multiple times:
-0: just print what is received
-1: escape non-printable characters, do newlines as unusual
-2: escape non-printable characters, newlines too
-3: hex dump everything""",
- default = 0
- )
-
- parser.add_option("--rts",
- dest = "rts_state",
- action = "store",
- type = 'int',
- help = "set initial RTS line state (possible values: 0, 1)",
- default = None
- )
-
- parser.add_option("--dtr",
- dest = "dtr_state",
- action = "store",
- type = 'int',
- help = "set initial DTR line state (possible values: 0, 1)",
- default = None
- )
-
- parser.add_option("-q", "--quiet",
- dest = "quiet",
- action = "store_true",
- help = "suppress non error messages",
- default = False
- )
-
- parser.add_option("--exit-char",
- dest = "exit_char",
- action = "store",
- type = 'int',
- help = "ASCII code of special character that is used to exit the application",
- default = 0x1d
- )
-
- parser.add_option("--menu-char",
- dest = "menu_char",
- action = "store",
- type = 'int',
- help = "ASCII code of special character that is used to control miniterm (menu)",
- default = 0x14
- )
-
- (options, args) = parser.parse_args()
-
- options.parity = options.parity.upper()
- if options.parity not in 'NEOSM':
- parser.error("invalid parity")
-
- if options.cr and options.lf:
- parser.error("only one of --cr or --lf can be specified")
-
- if options.menu_char == options.exit_char:
- parser.error('--exit-char can not be the same as --menu-char')
-
- global EXITCHARCTER, MENUCHARACTER
- EXITCHARCTER = chr(options.exit_char)
- MENUCHARACTER = chr(options.menu_char)
-
- port = options.port
- baudrate = options.baudrate
- if args:
- if options.port is not None:
- parser.error("no arguments are allowed, options only when --port is given")
- port = args.pop(0)
- if args:
- try:
- baudrate = int(args[0])
- except ValueError:
- parser.error("baud rate must be a number, not %r" % args[0])
- args.pop(0)
- if args:
- parser.error("too many arguments")
- else:
- if port is None: port = 0
-
- convert_outgoing = CONVERT_CRLF
- if options.cr:
- convert_outgoing = CONVERT_CR
- elif options.lf:
- convert_outgoing = CONVERT_LF
-
- try:
- miniterm = Miniterm(
- port,
- baudrate,
- options.parity,
- rtscts=options.rtscts,
- xonxoff=options.xonxoff,
- echo=options.echo,
- convert_outgoing=convert_outgoing,
- repr_mode=options.repr_mode,
- )
- except serial.SerialException, e:
- sys.stderr.write("could not open port %r: %s\n" % (port, e))
- sys.exit(1)
-
- if not options.quiet:
- sys.stderr.write('--- Miniterm on %s: %d,%s,%s,%s ---\n' % (
- miniterm.serial.portstr,
- miniterm.serial.baudrate,
- miniterm.serial.bytesize,
- miniterm.serial.parity,
- miniterm.serial.stopbits,
- ))
- sys.stderr.write('--- Quit: %s | Menu: %s | Help: %s followed by %s ---\n' % (
- key_description(EXITCHARCTER),
- key_description(MENUCHARACTER),
- key_description(MENUCHARACTER),
- key_description('\x08'),
- ))
-
- if options.dtr_state is not None:
- if not options.quiet:
- sys.stderr.write('--- forcing DTR %s\n' % (options.dtr_state and 'active' or 'inactive'))
- miniterm.serial.setDTR(options.dtr_state)
- miniterm.dtr_state = options.dtr_state
- if options.rts_state is not None:
- if not options.quiet:
- sys.stderr.write('--- forcing RTS %s\n' % (options.rts_state and 'active' or 'inactive'))
- miniterm.serial.setRTS(options.rts_state)
- miniterm.rts_state = options.rts_state
-
- miniterm.start()
- try:
- miniterm.join(True)
- except KeyboardInterrupt:
- pass
- if not options.quiet:
- sys.stderr.write("\n--- exit ---\n")
- miniterm.join()
-
-
-if __name__ == '__main__':
- main()
diff --git a/python-serial/pyserial/documentation/Makefile b/python-serial/pyserial/documentation/Makefile
deleted file mode 100644
index 8384360..0000000
--- a/python-serial/pyserial/documentation/Makefile
+++ /dev/null
@@ -1,88 +0,0 @@
-# Makefile for Sphinx documentation
-#
-
-# You can set these variables from the command line.
-SPHINXOPTS =
-SPHINXBUILD = sphinx-build
-PAPER =
-
-# Internal variables.
-PAPEROPT_a4 = -D latex_paper_size=a4
-PAPEROPT_letter = -D latex_paper_size=letter
-ALLSPHINXOPTS = -d _build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
-
-.PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest
-
-help:
- @echo "Please use \`make ' where is one of"
- @echo " html to make standalone HTML files"
- @echo " dirhtml to make HTML files named index.html in directories"
- @echo " pickle to make pickle files"
- @echo " json to make JSON files"
- @echo " htmlhelp to make HTML files and a HTML help project"
- @echo " qthelp to make HTML files and a qthelp project"
- @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
- @echo " changes to make an overview of all changed/added/deprecated items"
- @echo " linkcheck to check all external links for integrity"
- @echo " doctest to run all doctests embedded in the documentation (if enabled)"
-
-clean:
- -rm -rf _build/*
-
-html:
- $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) _build/html
- @echo
- @echo "Build finished. The HTML pages are in _build/html."
-
-dirhtml:
- $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) _build/dirhtml
- @echo
- @echo "Build finished. The HTML pages are in _build/dirhtml."
-
-pickle:
- $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) _build/pickle
- @echo
- @echo "Build finished; now you can process the pickle files."
-
-json:
- $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) _build/json
- @echo
- @echo "Build finished; now you can process the JSON files."
-
-htmlhelp:
- $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) _build/htmlhelp
- @echo
- @echo "Build finished; now you can run HTML Help Workshop with the" \
- ".hhp project file in _build/htmlhelp."
-
-qthelp:
- $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) _build/qthelp
- @echo
- @echo "Build finished; now you can run "qcollectiongenerator" with the" \
- ".qhcp project file in _build/qthelp, like this:"
- @echo "# qcollectiongenerator _build/qthelp/pySerial.qhcp"
- @echo "To view the help file:"
- @echo "# assistant -collectionFile _build/qthelp/pySerial.qhc"
-
-latex:
- $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) _build/latex
- @echo
- @echo "Build finished; the LaTeX files are in _build/latex."
- @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \
- "run these through (pdf)latex."
-
-changes:
- $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) _build/changes
- @echo
- @echo "The overview file is in _build/changes."
-
-linkcheck:
- $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) _build/linkcheck
- @echo
- @echo "Link check complete; look for any errors in the above output " \
- "or in _build/linkcheck/output.txt."
-
-doctest:
- $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) _build/doctest
- @echo "Testing of doctests in the sources finished, look at the " \
- "results in _build/doctest/output.txt."
diff --git a/python-serial/pyserial/documentation/appendix.rst b/python-serial/pyserial/documentation/appendix.rst
deleted file mode 100644
index 2c3a549..0000000
--- a/python-serial/pyserial/documentation/appendix.rst
+++ /dev/null
@@ -1,138 +0,0 @@
-==========
- Appendix
-==========
-
-How To
-======
-
-Enable :rfc:`2217` in programs using pySerial.
- Patch the code where the :class:`serial.Serial` is instantiated. Replace
- it with::
-
- try:
- s = serial.serial_for_url(...)
- except AttributeError:
- s = serial.Serial(...)
-
- Assuming the application already stores port names as strings that's all
- that is required. The user just needs a way to change the port setting of
- your application to an ``rfc2217://`` :ref:`URL ` (e.g. by editing a
- configuration file, GUI dialog etc.).
-
- Please note that this enables all :ref:`URL ` types supported by
- pySerial and that those involving the network are unencrypted and not
- protected against eavesdropping.
-
-Test your setup.
- Is the device not working as expected? Maybe it's time to check the
- connection before proceeding. :ref:`miniterm` from the :ref:`examples`
- can be used to open the serial port and do some basic tests.
-
- To test cables, connecting RX to TX (loop back) and typing some characters
- in :ref:`miniterm` is a simple test. When the characters are displayed
- on the screen, then at least RX and TX work (they still could be swapped
- though).
-
-
-FAQ
-===
-Example works in :ref:`miniterm` but not in script.
- The RTS and DTR lines are switched when the port is opened. This may cause
- some processing or reset on the connected device. In such a cases an
- immediately following call to :meth:`write` may not be received by the
- device.
-
- A delay after opening the port, before the first :meth:`write`, is
- recommended in this situation. E.g. a ``time.sleep(1)``
-
-
-Application works when .py file is run, but fails when packaged (py2exe etc.)
- py2exe and similar packaging programs scan the sources for import
- statements and create a list of modules that they package. pySerial may
- create two issues with that:
-
- - implementations for other modules are found. On Windows, it's safe to
- exclude 'serialposix', 'serialjava' and 'serialcli' as these are not
- used.
-
- - :func:`serial.serial_for_url` does a dynamic lookup of protocol handlers
- at runtime. If this function is used, the desired handlers have to be
- included manually (e.g. 'serial.urlhandler.protocol_socket',
- 'serial.urlhandler.protocol_rfc2217', etc.). This can be done either with
- the "includes" option in ``setup.py`` or by a dummy import in one of the
- packaged modules.
-
-User supplied URL handlers
- :func:`serial.serial_for_url` can be used to access "virtual" serial ports
- identified by an :ref:`URL ` scheme. E.g. for the :rfc:`2217`:
- ``rfc2217:://``.
-
- Custom :ref:`URL ` handlers can be added by extending the module
- search path in :data:`serial.protocol_handler_packages`. This is possible
- starting from pySerial V2.6.
-
-
-Related software
-================
-
-com0com - http://com0com.sourceforge.net/
- Provides virtual serial ports for Windows.
-
-
-License
-=======
-
-Copyright (C) 2001-2011 Chris Liechti ;
-All Rights Reserved.
-
-This is the Python license. In short, you can use this product in commercial
-and non-commercial applications, modify it, redistribute it. A notification to
-the author when you use and/or modify it is welcome.
-
-
-**TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING THIS SOFTWARE**
-
-*LICENSE AGREEMENT*
-
-1. This LICENSE AGREEMENT is between the copyright holder of this product, and
- the Individual or Organization ("Licensee") accessing and otherwise using
- this product in source or binary form and its associated documentation.
-
-2. Subject to the terms and conditions of this License Agreement, the copyright
- holder hereby grants Licensee a nonexclusive, royalty-free, world-wide
- license to reproduce, analyze, test, perform and/or display publicly,
- prepare derivative works, distribute, and otherwise use this product alone
- or in any derivative version, provided, however, that copyright holders
- License Agreement and copyright holders notice of copyright are retained in
- this product alone or in any derivative version prepared by Licensee.
-
-3. In the event Licensee prepares a derivative work that is based on or
- incorporates this product or any part thereof, and wants to make the
- derivative work available to others as provided herein, then Licensee hereby
- agrees to include in any such work a brief summary of the changes made to
- this product.
-
-4. The copyright holder is making this product available to Licensee on an "AS
- IS" basis. THE COPYRIGHT HOLDER MAKES NO REPRESENTATIONS OR WARRANTIES,
- EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, THE COPYRIGHT
- HOLDER MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF
- MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF
- THIS PRODUCT WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
-
-5. THE COPYRIGHT HOLDER SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF
- THIS PRODUCT FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
- AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING THIS PRODUCT, OR
- ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
-
-6. This License Agreement will automatically terminate upon a material breach
- of its terms and conditions.
-
-7. Nothing in this License Agreement shall be deemed to create any relationship
- of agency, partnership, or joint venture between the copyright holder and
- Licensee. This License Agreement does not grant permission to use trademarks
- or trade names from the copyright holder in a trademark sense to endorse or
- promote products or services of Licensee, or any third party.
-
-8. By copying, installing or otherwise using this product, Licensee agrees to
- be bound by the terms and conditions of this License Agreement.
-
diff --git a/python-serial/pyserial/documentation/conf.py b/python-serial/pyserial/documentation/conf.py
deleted file mode 100644
index af724a5..0000000
--- a/python-serial/pyserial/documentation/conf.py
+++ /dev/null
@@ -1,200 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# pySerial documentation build configuration file, created by
-# sphinx-quickstart on Tue Jul 21 00:27:45 2009.
-#
-# This file is execfile()d with the current directory set to its containing dir.
-#
-# Note that not all possible configuration values are present in this
-# autogenerated file.
-#
-# All configuration values have a default; values that are commented out
-# serve to show the default.
-
-import sys, os
-
-# If extensions (or modules to document with autodoc) are in another directory,
-# add these directories to sys.path here. If the directory is relative to the
-# documentation root, use os.path.abspath to make it absolute, like shown here.
-#sys.path.append(os.path.abspath('.'))
-
-# -- General configuration -----------------------------------------------------
-
-# Add any Sphinx extension module names here, as strings. They can be extensions
-# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
-extensions = ['sphinx.ext.intersphinx']
-
-# Add any paths that contain templates here, relative to this directory.
-templates_path = ['_templates']
-
-# The suffix of source filenames.
-source_suffix = '.rst'
-
-# The encoding of source files.
-#source_encoding = 'utf-8'
-
-# The master toctree document.
-master_doc = 'index'
-
-# General information about the project.
-project = u'pySerial'
-copyright = u'2001-2010, Chris Liechti'
-
-# The version info for the project you're documenting, acts as replacement for
-# |version| and |release|, also used in various other places throughout the
-# built documents.
-#
-# The short X.Y version.
-version = '2.6'
-# The full version, including alpha/beta/rc tags.
-release = '2.6'
-
-# The language for content autogenerated by Sphinx. Refer to documentation
-# for a list of supported languages.
-#language = None
-
-# There are two options for replacing |today|: either, you set today to some
-# non-false value, then it is used:
-#today = ''
-# Else, today_fmt is used as the format for a strftime call.
-#today_fmt = '%B %d, %Y'
-
-# List of documents that shouldn't be included in the build.
-#unused_docs = []
-
-# List of directories, relative to source directory, that shouldn't be searched
-# for source files.
-exclude_trees = ['_build']
-
-# The reST default role (used for this markup: `text`) to use for all documents.
-#default_role = None
-
-# If true, '()' will be appended to :func: etc. cross-reference text.
-#add_function_parentheses = True
-
-# If true, the current module name will be prepended to all description
-# unit titles (such as .. function::).
-#add_module_names = True
-
-# If true, sectionauthor and moduleauthor directives will be shown in the
-# output. They are ignored by default.
-#show_authors = False
-
-# The name of the Pygments (syntax highlighting) style to use.
-pygments_style = 'sphinx'
-
-# A list of ignored prefixes for module index sorting.
-#modindex_common_prefix = []
-
-
-# -- Options for HTML output ---------------------------------------------------
-
-# The theme to use for HTML and HTML Help pages. Major themes that come with
-# Sphinx are currently 'default' and 'sphinxdoc'.
-html_theme = 'default'
-
-# Theme options are theme-specific and customize the look and feel of a theme
-# further. For a list of options available for each theme, see the
-# documentation.
-#html_theme_options = {}
-
-# Add any paths that contain custom themes here, relative to this directory.
-#html_theme_path = []
-
-# The name for this set of Sphinx documents. If None, it defaults to
-# " v documentation".
-#html_title = None
-
-# A shorter title for the navigation bar. Default is the same as html_title.
-#html_short_title = None
-
-# The name of an image file (relative to this directory) to place at the top
-# of the sidebar.
-html_logo = 'pyserial.png'
-
-# The name of an image file (within the static path) to use as favicon of the
-# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
-# pixels large.
-#html_favicon = None
-
-# Add any paths that contain custom static files (such as style sheets) here,
-# relative to this directory. They are copied after the builtin static files,
-# so a file named "default.css" will overwrite the builtin "default.css".
-html_static_path = ['_static']
-
-# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
-# using the given strftime format.
-#html_last_updated_fmt = '%b %d, %Y'
-
-# If true, SmartyPants will be used to convert quotes and dashes to
-# typographically correct entities.
-#html_use_smartypants = True
-
-# Custom sidebar templates, maps document names to template names.
-#html_sidebars = {}
-
-# Additional templates that should be rendered to pages, maps page names to
-# template names.
-#html_additional_pages = {}
-
-# If false, no module index is generated.
-#html_use_modindex = True
-
-# If false, no index is generated.
-#html_use_index = True
-
-# If true, the index is split into individual pages for each letter.
-#html_split_index = False
-
-# If true, links to the reST sources are added to the pages.
-#html_show_sourcelink = True
-
-# If true, an OpenSearch description file will be output, and all pages will
-# contain a tag referring to it. The value of this option must be the
-# base URL from which the finished HTML is served.
-#html_use_opensearch = ''
-
-# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
-#html_file_suffix = ''
-
-# Output file base name for HTML help builder.
-htmlhelp_basename = 'pySerialdoc'
-
-
-# -- Options for LaTeX output --------------------------------------------------
-
-# The paper size ('letter' or 'a4').
-#latex_paper_size = 'letter'
-
-# The font size ('10pt', '11pt' or '12pt').
-#latex_font_size = '10pt'
-
-# Grouping the document tree into LaTeX files. List of tuples
-# (source start file, target name, title, author, documentclass [howto/manual]).
-latex_documents = [
- ('index', 'pySerial.tex', u'pySerial Documentation',
- u'Chris Liechti', 'manual'),
-]
-
-# The name of an image file (relative to this directory) to place at the top of
-# the title page.
-latex_logo = 'pyserial.png'
-
-# For "manual" documents, if this is true, then toplevel headings are parts,
-# not chapters.
-#latex_use_parts = False
-
-# Additional stuff for the LaTeX preamble.
-#latex_preamble = ''
-
-# Documents to append as an appendix to all manuals.
-#latex_appendices = []
-
-# If false, no module index is generated.
-#latex_use_modindex = True
-
-# for external links to standard library
-intersphinx_mapping = {
- #~ 'python': ('http://docs.python.org', None),
- 'py': ('http://docs.python.org', None),
- }
diff --git a/python-serial/pyserial/documentation/examples.rst b/python-serial/pyserial/documentation/examples.rst
deleted file mode 100644
index 39f238c..0000000
--- a/python-serial/pyserial/documentation/examples.rst
+++ /dev/null
@@ -1,341 +0,0 @@
-.. _examples:
-
-==========
- Examples
-==========
-
-.. _miniterm:
-
-Miniterm
-========
-This is a console application that provides a small terminal application.
-Miniterm itself does not implement any terminal features such as VT102
-compatibility. However it inherits these features from the terminal it is run.
-For example on GNU/Linux running from an xterm it will support the escape
-sequences of the xterm. On Windows the typical console window is dumb and does
-not support any escapes. When ANSI.sys is loaded it supports some escapes.
-
-Miniterm::
-
- --- Miniterm on /dev/ttyS0: 9600,8,N,1 ---
- --- Quit: Ctrl+] | Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H ---
-
-Command line options can be given so that binary data including escapes for
-terminals are escaped or output as hex.
-
-Miniterm supports :rfc:`2217` remote serial ports and raw sockets using :ref:`URLs`
-such as ``rfc2217:://:`` respectively ``socket://:`` as
-*port* argument when invoking.
-
-Command line options ``python -m serial.tools.miniterm -h``::
-
- Usage: miniterm.py [options] [port [baudrate]]
-
- Miniterm - A simple terminal program for the serial port.
-
- Options:
- -h, --help show this help message and exit
- -p PORT, --port=PORT port, a number (default 0) or a device name
- (deprecated option)
- -b BAUDRATE, --baud=BAUDRATE
- set baud rate, default 9600
- --parity=PARITY set parity, one of [N, E, O, S, M], default=N
- -e, --echo enable local echo (default off)
- --rtscts enable RTS/CTS flow control (default off)
- --xonxoff enable software flow control (default off)
- --cr do not send CR+LF, send CR only
- --lf do not send CR+LF, send LF only
- -D, --debug debug received data (escape non-printable chars)
- --debug can be given multiple times: 0: just print
- what is received 1: escape non-printable characters,
- do newlines as unusual 2: escape non-printable
- characters, newlines too 3: hex dump everything
- --rts=RTS_STATE set initial RTS line state (possible values: 0, 1)
- --dtr=DTR_STATE set initial DTR line state (possible values: 0, 1)
- -q, --quiet suppress non error messages
- --exit-char=EXIT_CHAR
- ASCII code of special character that is used to exit
- the application
- --menu-char=MENU_CHAR
- ASCII code of special character that is used to
- control miniterm (menu)
-
-
-Miniterm supports some control functions. Typing :kbd:`Ctrl+T Ctrl+H` when it is
-running shows the help text::
-
- --- pySerial - miniterm - help
- ---
- --- Ctrl+] Exit program
- --- Ctrl+T Menu escape key, followed by:
- --- Menu keys:
- --- Ctrl+T Send the menu character itself to remote
- --- Ctrl+] Send the exit character to remote
- --- Ctrl+I Show info
- --- Ctrl+U Upload file (prompt will be shown)
- --- Toggles:
- --- Ctrl+R RTS Ctrl+E local echo
- --- Ctrl+D DTR Ctrl+B BREAK
- --- Ctrl+L line feed Ctrl+A Cycle repr mode
- ---
- --- Port settings (Ctrl+T followed by the following):
- --- p change port
- --- 7 8 set data bits
- --- n e o s m change parity (None, Even, Odd, Space, Mark)
- --- 1 2 3 set stop bits (1, 2, 1.5)
- --- b change baud rate
- --- x X disable/enable software flow control
- --- r R disable/enable hardware flow control
-
-.. versionchanged:: 2.5
- Added :kbd:`Ctrl+T` menu and added support for opening URLs.
-.. versionchanged:: 2.6
- File moved from the examples to :mod:`serial.tools.miniterm`.
-
-miniterm.py_
- The miniterm program.
-
-setup-miniterm-py2exe.py_
- This is a py2exe setup script for Windows. It can be used to create a
- standalone ``miniterm.exe``.
-
-.. _miniterm.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/serial/tools/miniterm.py
-.. _setup-miniterm-py2exe.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/setup-miniterm-py2exe.py
-
-
-TCP/IP - serial bridge
-======================
-This program opens a TCP/IP port. When a connection is made to that port (e.g.
-with telnet) it forwards all data to the serial port and vice versa.
-
-This example only exports a raw socket connection. The next example
-below gives the client much more control over the remote serial port.
-
-- The serial port settings are set on the command line when starting the
- program.
-- There is no possibility to change settings from remote.
-- All data is passed through as-is.
-
-::
-
- Usage: tcp_serial_redirect.py [options] [port [baudrate]]
-
- Simple Serial to Network (TCP/IP) redirector.
-
- Options:
- -h, --help show this help message and exit
- -q, --quiet suppress non error messages
- --spy peek at the communication and print all data to the
- console
-
- Serial Port:
- Serial port settings
-
- -p PORT, --port=PORT
- port, a number (default 0) or a device name
- -b BAUDRATE, --baud=BAUDRATE
- set baud rate, default: 9600
- --parity=PARITY set parity, one of [N, E, O], default=N
- --rtscts enable RTS/CTS flow control (default off)
- --xonxoff enable software flow control (default off)
- --rts=RTS_STATE set initial RTS line state (possible values: 0, 1)
- --dtr=DTR_STATE set initial DTR line state (possible values: 0, 1)
-
- Network settings:
- Network configuration.
-
- -P LOCAL_PORT, --localport=LOCAL_PORT
- local TCP port
- --rfc2217 allow control commands with Telnet extension RFC-2217
-
- Newline Settings:
- Convert newlines between network and serial port. Conversion is
- normally disabled and can be enabled by --convert.
-
- -c, --convert enable newline conversion (default off)
- --net-nl=NET_NEWLINE
- type of newlines that are expected on the network
- (default: LF)
- --ser-nl=SER_NEWLINE
- type of newlines that are expected on the serial port
- (default: CR+LF)
-
- NOTE: no security measures are implemented. Anyone can remotely connect to
- this service over the network. Only one connection at once is supported. When
- the connection is terminated it waits for the next connect.
-
-
-tcp_serial_redirect.py_
- Main program.
-
-.. _tcp_serial_redirect.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/tcp_serial_redirect.py
-
-Single-port TCP/IP - serial bridge (RFC 2217)
-=============================================
-Simple cross platform :rfc:`2217` serial port server. It uses threads and is
-portable (runs on POSIX, Windows, etc).
-
-- The port settings and control lines (RTS/DTR) can be changed at any time
- using :rfc:`2217` requests. The status lines (DSR/CTS/RI/CD) are polled every
- second and notifications are sent to the client.
-- Telnet character IAC (0xff) needs to be doubled in data stream. IAC followed
- by an other value is interpreted as Telnet command sequence.
-- Telnet negotiation commands are sent when connecting to the server.
-- RTS/DTR are activated on client connect and deactivated on disconnect.
-- Default port settings are set again when client disconnects.
-
-::
-
- Usage: rfc2217_server.py [options] port
-
- RFC 2217 Serial to Network (TCP/IP) redirector.
-
- Options:
- -h, --help show this help message and exit
- -p LOCAL_PORT, --localport=LOCAL_PORT
- local TCP port
-
- NOTE: no security measures are implemented. Anyone can remotely connect to
- this service over the network. Only one connection at once is supported. When
- the connection is terminated it waits for the next connect.
-
-.. versionadded:: 2.5
-
-rfc2217_server.py_
- Main program.
-
-setup-rfc2217_server-py2exe.py_
- This is a py2exe setup script for Windows. It can be used to create a
- standalone ``rfc2217_server.exe``.
-
-.. _rfc2217_server.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/rfc2217_server.py
-.. _setup-rfc2217_server-py2exe.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/setup-rfc2217_server-py2exe.py
-
-
-Multi-port TCP/IP - serial bridge (RFC 2217)
-============================================
-This example implements a TCP/IP to serial port service that works with
-multiple ports at once. It uses select, no threads, for the serial ports and
-the network sockets and therefore runs on POSIX systems only.
-
-- Full control over the serial port with :rfc:`2217`.
-- Check existence of ``/tty/USB0...8``. This is done every 5 seconds using
- ``os.path.exists``.
-- Send zeroconf announcements when port appears or disappears (uses
- python-avahi and dbus). Service name: ``_serial_port._tcp``.
-- Each serial port becomes available as one TCP/IP server. e.g.
- ``/dev/ttyUSB0`` is reachable at ``:7000``.
-- Single process for all ports and sockets (not per port).
-- The script can be started as daemon.
-- Logging to stdout or when run as daemon to syslog.
-- Default port settings are set again when client disconnects.
-- modem status lines (CTS/DSR/RI/CD) are not polled periodically and the server
- therefore does not send NOTIFY_MODEMSTATE on its own. However it responds to
- request from the client (i.e. use the ``poll_modem`` option in the URL when
- using a pySerial client.)
-
-Requirements:
-
-- Python (>= 2.4)
-- python-avahi
-- python-dbus
-- python-serial (>= 2.5)
-
-Installation as daemon:
-
-- Copy the script ``port_publisher.py`` to ``/usr/local/bin``.
-- Copy the script ``port_publisher.sh`` to ``/etc/init.d``.
-- Add links to the runlevels using ``update-rc.d port_publisher.sh defaults 99``
-- Thats it :-) the service will be started on next reboot. Alternatively run
- ``invoke-rc.d port_publisher.sh start`` as root.
-
-.. versionadded:: 2.5 new example
-
-port_publisher.py_
- Multi-port TCP/IP-serial converter (RFC 2217) for POSIX environments.
-
-port_publisher.sh_
- Example init.d script.
-
-.. _port_publisher.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/port_publisher.py
-.. _port_publisher.sh: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/port_publisher.sh
-
-
-wxPython examples
-=================
-A simple terminal application for wxPython and a flexible serial port
-configuration dialog are shown here.
-
-wxTerminal.py_
- A simple terminal application. Note that the length of the buffer is
- limited by wx and it may suddenly stop displaying new input.
-
-wxTerminal.wxg_
- A wxGlade design file for the terminal application.
-
-wxSerialConfigDialog.py_
- A flexible serial port configuration dialog.
-
-wxSerialConfigDialog.wxg_
- The wxGlade design file for the configuration dialog.
-
-setup-wxTerminal-py2exe.py_
- A py2exe setup script to package the terminal application.
-
-.. _wxTerminal.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/wxTerminal.py
-.. _wxTerminal.wxg: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/wxTerminal.wxg
-.. _wxSerialConfigDialog.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/wxSerialConfigDialog.py
-.. _wxSerialConfigDialog.wxg: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/wxSerialConfigDialog.wxg
-.. _setup-wxTerminal-py2exe.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/setup-wxTerminal-py2exe.py
-
-
-Wrapper class
-=============
-This example provides a subclass based on ``Serial`` that has an alternative
-implementation of ``readline()``
-
-enhancedserial.py_
- A class with alternative ``readline()`` implementation.
-
-.. _enhancedserial.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/examples/enhancedserial.py
-
-
-Unit tests
-==========
-The project uses a number of unit test to verify the functionality. They all
-need a loop back connector. The scripts itself contain more information. All
-test scripts are contained in the directory ``test``.
-
-The unit tests are performed on port ``0`` unless a different device name or
-``rfc2217://`` URL is given on the command line (argv[1]).
-
-run_all_tests.py_
- Collect all tests from all ``test*`` files and run them. By default, the
- ``loop://`` device is used.
-
-test.py_
- Basic tests (binary capabilities, timeout, control lines).
-
-test_advanced.py_
- Test more advanced features (properties).
-
-test_high_load.py_
- Tests involving sending a lot of data.
-
-test_readline.py_
- Tests involving readline.
-
-test_iolib.py_
- Tests involving the :mod:`io` library. Only available for Python 2.6 and
- newer.
-
-test_url.py_
- Tests involving the :ref:`URL ` feature.
-
-.. _run_all_tests.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/test/run_all_tests.py
-.. _test.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/test/test.py
-.. _test_advanced.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/test/test_advanced.py
-.. _test_high_load.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/test/test_high_load.py
-.. _test_readline.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/test/test_readline.py
-.. _test_iolib.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/test/test_iolib.py
-.. _test_url.py: http://pyserial.svn.sourceforge.net/viewvc/*checkout*/pyserial/trunk/pyserial/test/test_url.py
diff --git a/python-serial/pyserial/documentation/index.rst b/python-serial/pyserial/documentation/index.rst
deleted file mode 100644
index ed306ba..0000000
--- a/python-serial/pyserial/documentation/index.rst
+++ /dev/null
@@ -1,41 +0,0 @@
-.. pySerial documentation master file
-
-Welcome to pySerial's documentation
-===================================
-
-This module encapsulates the access for the serial port. It provides backends
-for Python running on Windows, Linux, BSD (possibly any POSIX compliant
-system), Jython and IronPython (.NET and Mono). The module named "serial"
-automatically selects the appropriate backend.
-
-Other pages (online)
-
-- `project page on SourceForge`_
-- `SVN repository`_
-- `Download Page`_ with releases
-- This page, when viewed online, is at http://pyserial.sf.net.
-
-.. _`project page on SourceForge`: http://sourceforge.net/projects/pyserial/
-.. _`SVN repository`: http://sourceforge.net/svn/?group_id=46487
-.. _`Download Page`: http://pypi.python.org/pypi/pyserial
-
-
-Contents:
-
-.. toctree::
- :maxdepth: 2
-
- pyserial
- shortintro
- examples
- pyserial_api
- pyparallel
- appendix
-
-Indices and tables
-==================
-
-* :ref:`genindex`
-* :ref:`modindex`
-* :ref:`search`
-
diff --git a/python-serial/pyserial/documentation/pyparallel.rst b/python-serial/pyserial/documentation/pyparallel.rst
deleted file mode 100644
index 00c0b95..0000000
--- a/python-serial/pyserial/documentation/pyparallel.rst
+++ /dev/null
@@ -1,165 +0,0 @@
-============
- pyParallel
-============
-
-.. note:: This module is in development (since years ;-)
-
-Overview
-========
-This module encapsulates the access for the parallel port. It provides backends
-for Python running on Windows and Linux. Other platforms are possible too but
-not yet integrated.
-
-This module is still under development. But it may be useful for developers.
-
-Copyright (C) 2001-2003 Chris Liechti
-
-Here is the `project page on SourceForge`_ and here is the `SVN repository`_.
-
-.. _`project page on SourceForge`: http://sourceforge.net/projects/pyserial/
-.. _`SVN repository`: http://sourceforge.net/svn/?group_id=46487
-
-
-Features
---------
-* same class based interface on all supported platforms
-* port numbering starts at zero, no need to know the port name in the user program
-* port string (device name) can be specified if access through numbering is inappropriate
-
-
-Requirements
-------------
-* Python 2.2 or newer
-* "Java Communications" (JavaComm) extension for Java/Jython
-
-
-Installation
-------------
-Extract files from the archive, open a shell/console in that directory and let
-Distutils do the rest: ``python setup.py install``
-
-The files get installed in the "Lib/site-packages" directory in newer Python versions.
-
-The windows version needs a compiled extension and the giveio.sys driver for
-Windows NT/2k/XP. The extension module can be compiled with Distutils with
-either MSVC or GCC/mingw32.
-
-It is released under a free software license, see LICENSE.txt for more details.
-
-
-Short introduction
-==================
-::
-
- >>> import parallel
- >>> p = parallel.Parallel() # open LPT1
- >>> p.setData(0x55)
-
-
-Examples
---------
-Please look in the SVN Repository. There is an example directory where you can
-find a simple terminal and more.
-http://pyserial.svn.sourceforge.net/viewvc/pyserial/trunk/pyparallel/examples/
-
-
-API
-===
-
-.. module:: parallel
-
-.. class:: Parallel
-
- .. method:: __init__(port)
-
- Open given parallel port.
-
- .. method:: setData(value)
-
- Apply the given byte to the data pins of the parallel port.
-
- .. method:: setDataStrobe(level)
-
- Set the "data strobe" line to the given state.
-
- .. method:: setAutoFeed(level)
-
- Set "auto feed" line to given state.
-
- .. method:: setInitOut(level)
-
- Set "initialize" line to given state.
-
- .. method: setSelect(level)
-
- Set "select" line to given state.
-
- .. method:getInError()
-
- Set "Error" line to given state.
-
- .. method:: getInSelected()
-
- Read level of "select" line.
-
- .. method:: getInPaperOut()
-
- Read level of "paper out" line.
-
- .. method:: getInAcknowledge()
-
- Read level of "Acknowledge" line.
-
- .. method: getInBusy()
-
- Read level of "busy" line.
-
-
-.. module:: parallel.parallelutil
-
-.. class:: BitaccessMeta
-
- This mix-in class adds a few properties that allow easier bit access to the
- data lines. (D0 .. D7) e.g. p.D0 refers to the first bit of the data
- lines.
-
-.. class:: VirtualParallelPort
-
- This class provides a virtual parallel port implementation, useful
- for tests and simulations without real hardware.
-
-
-Notes
-=====
-
-Linux
------
-1. The :manpage:`lp(4)` module must be unloaded, ``rmmod lp``. ``lp`` claims
- exclusive access to the port and other programs won't be able to use it.
-
-2. The :manpage:`ppdev(4)` module needs to be loaded, ``modprobe ppdev``. When
- ``udev`` is in use, (default with 2.6 kernels) this will create a
- ``/dev/parport0``.
-
-3. The user needs to have write permissions to ``/dev/parport0``. Many
- distributions have an ``lp`` group that owns the device; the simplest is to
- add the user account to this group. Simply changing permissions on the
- device is not the best strategy as they will be reverted to their defaults
- next time the driver is loaded.
-
-
-Windows
--------
-The giveio driver must be installed as the module needs direct access to the
-hardware. This also means that USB parallel port adapters won't be supported.
-
-
-Misc
-====
-References
-----------
-* Python: http://www.python.org/
-* Jython: http://www.jython.org/
-* Java@IBM: http://www-106.ibm.com/developerworks/java/jdk/ (JavaComm links are
- on the download page for the respective platform JDK)
-* Java@SUN: http://java.sun.com/products/
diff --git a/python-serial/pyserial/documentation/pyserial.png b/python-serial/pyserial/documentation/pyserial.png
deleted file mode 100644
index 7fd45f4..0000000
Binary files a/python-serial/pyserial/documentation/pyserial.png and /dev/null differ
diff --git a/python-serial/pyserial/documentation/pyserial.rst b/python-serial/pyserial/documentation/pyserial.rst
deleted file mode 100644
index 017e6bc..0000000
--- a/python-serial/pyserial/documentation/pyserial.rst
+++ /dev/null
@@ -1,122 +0,0 @@
-==========
- pySerial
-==========
-
-Overview
-========
-This module encapsulates the access for the serial port. It provides backends
-for Python running on Windows, Linux, BSD (possibly any POSIX compliant
-system), Jython and IronPython (.NET and Mono). The module named "serial"
-automatically selects the appropriate backend.
-
-It is released under a free software license, see LICENSE_ for more
-details.
-
-Copyright (C) 2001-2010 Chris Liechti
-
-Other pages (online)
-
-- `project page on SourceForge`_
-- `SVN repository`_
-- `Download Page`_ with releases
-- This page, when viewed online is at http://pyserial.sf.net.
-
-.. _LICENSE: appendix.html#license
-.. _`project page on SourceForge`: http://sourceforge.net/projects/pyserial/
-.. _`SVN repository`: http://sourceforge.net/svn/?group_id=46487
-.. _`Download Page`: http://sourceforge.net/project/showfiles.php?group_id=46487
-
-
-Features
-========
-- Same class based interface on all supported platforms.
-- Access to the port settings through Python properties.
-- Support for different byte sizes, stop bits, parity and flow control with
- RTS/CTS and/or Xon/Xoff.
-- Working with or without receive timeout.
-- File like API with "read" and "write" ("readline" etc. also supported).
-- The files in this package are 100% pure Python.
-- The port is set up for binary transmission. No NULL byte stripping, CR-LF
- translation etc. (which are many times enabled for POSIX.) This makes this
- module universally useful.
-- Compatible with :mod:`io` library (Python 2.6+)
-- RFC 2217 client (experimental), server provided in the examples.
-
-
-Requirements
-============
-- Python 2.3 or newer, including Python 3.x
-- ctypes extensions on Windows (is in standard library since Python 2.5+)
-- "Java Communications" (JavaComm) or compatible extension for Java/Jython
-
-
-Installation
-============
-
-pyserial
---------
-This installs a package that can be used from Python (``import serial``).
-
-To install the module for all users on the system, administrator rights (root)
-is required..
-
-From source (tar.gz or checkout)
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Download the archive from http://pypi.python.org/pypi/pyserial.
-Unpack the archive, enter the ``pyserial-x.y`` directory and run::
-
- python setup.py install
-
-For Python 3.x::
-
- python3 setup.py install
-
-From PyPI
-~~~~~~~~~
-Alternatively it can be installed from PyPI, either manually downloading the
-files and installing as described above or using::
-
- pip pyserial
-
-or::
-
- easy_install -U pyserial
-
-Packages
-~~~~~~~~
-There are also packaged versions for some Linux distributions and Windows:
-
-Debian/Ubuntu
- A package is available under the name "python-serial". Note that some
- distributions package an older version of pySerial.
-
-Windows
- There is also a Windows installer for end users. It is located in the
- PyPi_. Developers may be interested to get the source archive, because it
- contains examples and the readme.
-
-.. _PyPi: http://pypi.python.org/pypi/pyserial
-
-
-References
-==========
-* Python: http://www.python.org/
-* Jython: http://www.jython.org/
-* Java@IBM: http://www-106.ibm.com/developerworks/java/jdk/ (JavaComm links are
- on the download page for the respective platform JDK)
-* Java@SUN: http://java.sun.com/products/
-* IronPython: http://www.codeplex.com/IronPython
-* setuptools: http://peak.telecommunity.com/DevCenter/setuptools
-
-
-Older Versions
-==============
-Older versions are still available on the `Download Page`_. pySerial 1.21 is
-compatible with Python 2.0 on Windows, Linux and several un*x like systems,
-MacOSX and Jython.
-
-On windows releases older than 2.5 will depend on pywin32_ (previously known as
-win32all)
-
-.. _`Download Page`: http://sourceforge.net/project/showfiles.php?group_id=46487
-.. _pywin32: http://pypi.python.org/pypi/pywin32
diff --git a/python-serial/pyserial/documentation/pyserial_api.rst b/python-serial/pyserial/documentation/pyserial_api.rst
deleted file mode 100644
index 4849b23..0000000
--- a/python-serial/pyserial/documentation/pyserial_api.rst
+++ /dev/null
@@ -1,909 +0,0 @@
-==============
- pySerial API
-==============
-
-.. module:: serial
-
-Classes
-=======
-
-Native ports
-------------
-
-.. class:: Serial
-
- .. method:: __init__(port=None, baudrate=9600, bytesize=EIGHTBITS, parity=PARITY_NONE, stopbits=STOPBITS_ONE, timeout=None, xonxoff=False, rtscts=False, writeTimeout=None, dsrdtr=False, interCharTimeout=None)
-
- :param port:
- Device name or port number number or :const:`None`.
-
- :param baudrate:
- Baud rate such as 9600 or 115200 etc.
-
- :param bytesize:
- Number of data bits. Possible values:
- :const:`FIVEBITS`, :const:`SIXBITS`, :const:`SEVENBITS`,
- :const:`EIGHTBITS`
-
- :param parity:
- Enable parity checking. Possible values:
- :const:`PARITY_NONE`, :const:`PARITY_EVEN`, :const:`PARITY_ODD`
- :const:`PARITY_MARK`, :const:`PARITY_SPACE`
-
- :param stopbits:
- Number of stop bits. Possible values:
- :const:`STOPBITS_ONE`, :const:`STOPBITS_ONE_POINT_FIVE`,
- :const:`STOPBITS_TWO`
-
- :param timeout:
- Set a read timeout value.
-
- :param xonxoff:
- Enable software flow control.
-
- :param rtscts:
- Enable hardware (RTS/CTS) flow control.
-
- :param dsrdtr:
- Enable hardware (DSR/DTR) flow control.
-
- :param writeTimeout:
- Set a write timeout value.
-
- :param interCharTimeout:
- Inter-character timeout, :const:`None` to disable (default).
-
- :exception ValueError:
- Will be raised when parameter are out of range, e.g. baud rate, data bits.
-
- :exception SerialException:
- In case the device can not be found or can not be configured.
-
-
- The port is immediately opened on object creation, when a *port* is
- given. It is not opened when *port* is :const:`None` and a successive call
- to :meth:`open` will be needed.
-
- Possible values for the parameter *port*:
-
- - Number: number of device, numbering starts at zero.
- - Device name: depending on operating system. e.g. ``/dev/ttyUSB0``
- on GNU/Linux or ``COM3`` on Windows.
-
- The parameter *baudrate* can be one of the standard values:
- 50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800,
- 9600, 19200, 38400, 57600, 115200.
- These are well supported on all platforms. Standard values above 115200
- such as: 230400, 460800, 500000, 576000, 921600, 1000000, 1152000,
- 1500000, 2000000, 2500000, 3000000, 3500000, 4000000 also work on many
- platforms.
-
- Non-standard values are also supported on some platforms (GNU/Linux, MAC
- OSX >= Tiger, Windows). Though, even on these platforms some serial
- ports may reject non-standard values.
-
- Possible values for the parameter *timeout*:
-
- - ``timeout = None``: wait forever
- - ``timeout = 0``: non-blocking mode (return immediately on read)
- - ``timeout = x``: set timeout to ``x`` seconds (float allowed)
-
- Writes are blocking by default, unless *writeTimeout* is set. For
- possible values refer to the list for *timeout* above.
-
- Note that enabling both flow control methods (*xonxoff* and *rtscts*)
- together may not be supported. It is common to use one of the methods
- at once, not both.
-
- *dsrdtr* is not supported by all platforms (silently ignored). Setting
- it to ``None`` has the effect that its state follows *rtscts*.
-
- Also consider using the function :func:`serial_for_url` instead of
- creating Serial instances directly.
-
- .. versionchanged:: 2.5
- *dsrdtr* now defaults to ``False`` (instead of *None*)
-
- .. method:: open()
-
- Open port.
-
- .. method:: close()
-
- Close port immediately.
-
- .. method:: __del__()
-
- Destructor, close port when serial port instance is freed.
-
-
- The following methods may raise :exc:`ValueError` when applied to a closed
- port.
-
- .. method:: read(size=1)
-
- :param size: Number of bytes to read.
- :return: Bytes read from the port.
-
- Read *size* bytes from the serial port. If a timeout is set it may
- return less characters as requested. With no timeout it will block
- until the requested number of bytes is read.
-
- .. versionchanged:: 2.5
- Returns an instance of :class:`bytes` when available (Python 2.6
- and newer) and :class:`str` otherwise.
-
- .. method:: write(data)
-
- :param data: Data to send.
- :return: Number of bytes written.
- :exception SerialTimeoutException:
- In case a write timeout is configured for the port and the time is
- exceeded.
-
- Write the string *data* to the port.
-
- .. versionchanged:: 2.5
- Accepts instances of :class:`bytes` and :class:`bytearray` when
- available (Python 2.6 and newer) and :class:`str` otherwise.
-
- .. versionchanged:: 2.5
- Write returned ``None`` in previous versions.
-
- .. method:: inWaiting()
-
- Return the number of chars in the receive buffer.
-
- .. method:: flush()
-
- Flush of file like objects. In this case, wait until all data is
- written.
-
- .. method:: flushInput()
-
- Flush input buffer, discarding all it's contents.
-
- .. method:: flushOutput()
-
- Clear output buffer, aborting the current output and
- discarding all that is in the buffer.
-
- .. method:: sendBreak(duration=0.25)
-
- :param duration: Time (float) to activate the BREAK condition.
-
- Send break condition. Timed, returns to idle state after given
- duration.
-
- .. method:: setBreak(level=True)
-
- :param level: when true activate BREAK condition, else disable.
-
- Set break: Controls TXD. When active, no transmitting is possible.
-
- .. method:: setRTS(level=True)
-
- :param level: Set control line to logic level.
-
- Set RTS line to specified logic level.
-
- .. method:: setDTR(level=True)
-
- :param level: Set control line to logic level.
-
- Set DTR line to specified logic level.
-
- .. method:: getCTS()
-
- :return: Current state (boolean)
-
- Return the state of the CTS line.
-
- .. method:: getDSR()
-
- :return: Current state (boolean)
-
- Return the state of the DSR line.
-
- .. method:: getRI()
-
- :return: Current state (boolean)
-
- Return the state of the RI line.
-
- .. method:: getCD()
-
- :return: Current state (boolean)
-
- Return the state of the CD line
-
- Read-only attributes:
-
- .. attribute:: name
-
- Device name. This is always the device name even if the
- port was opened by a number. (Read Only).
-
- .. versionadded:: 2.5
-
- .. attribute:: portstr
-
- :deprecated: use :attr:`name` instead
-
- New values can be assigned to the following attributes (properties), the
- port will be reconfigured, even if it's opened at that time:
-
-
- .. attribute:: port
-
- Read or write port. When the port is already open, it will be closed
- and reopened with the new setting.
-
- .. attribute:: baudrate
-
- Read or write current baud rate setting.
-
- .. attribute:: bytesize
-
- Read or write current data byte size setting.
-
- .. attribute:: parity
-
- Read or write current parity setting.
-
- .. attribute:: stopbits
-
- Read or write current stop bit width setting.
-
- .. attribute:: timeout
-
- Read or write current read timeout setting.
-
- .. attribute:: writeTimeout
-
- Read or write current write timeout setting.
-
- .. attribute:: xonxoff
-
- Read or write current software flow control rate setting.
-
- .. attribute:: rtscts
-
- Read or write current hardware flow control setting.
-
- .. attribute:: dsrdtr
-
- Read or write current hardware flow control setting.
-
- .. attribute:: interCharTimeout
-
- Read or write current inter character timeout setting.
-
- The following constants are also provided:
-
- .. attribute:: BAUDRATES
-
- A list of valid baud rates. The list may be incomplete such that higher
- baud rates may be supported by the device and that values in between the
- standard baud rates are supported. (Read Only).
-
- .. attribute:: BYTESIZES
-
- A list of valid byte sizes for the device (Read Only).
-
- .. attribute:: PARITIES
-
- A list of valid parities for the device (Read Only).
-
- .. attribute:: STOPBITS
-
- A list of valid stop bit widths for the device (Read Only).
-
-
- The following methods are for compatibility with the :mod:`io` library.
-
- .. method:: readable()
-
- :return: True
-
- .. versionadded:: 2.5
-
- .. method:: writable()
-
- :return: True
-
- .. versionadded:: 2.5
-
- .. method:: seekable()
-
- :return: False
-
- .. versionadded:: 2.5
-
- .. method:: readinto(b)
-
- :param b: bytearray or array instance
- :return: Number of byte read
-
- Read up to len(b) bytes into :class:`bytearray` *b* and return the
- number of bytes read.
-
- .. versionadded:: 2.5
-
- The port settings can be read and written as dictionary.
-
- .. method:: getSettingsDict()
-
- :return: a dictionary with current port settings.
-
- Get a dictionary with port settings. This is useful to backup the
- current settings so that a later point in time they can be restored
- using :meth:`applySettingsDict`.
-
- Note that control lines (RTS/DTR) are part of the settings.
-
- .. versionadded:: 2.5
-
- .. method:: applySettingsDict(d)
-
- :param d: a dictionary with port settings.
-
- Applies a dictionary that was created by :meth:`getSettingsDict`. Only
- changes are applied and when a key is missing it means that the setting
- stays unchanged.
-
- Note that control lines (RTS/DTR) are not changed.
-
- .. versionadded:: 2.5
-
- Platform specific methods.
-
- .. warning:: Programs using the following methods are not portable to other platforms!
-
- .. method:: nonblocking()
-
- :platform: Unix
-
- Configure the device for nonblocking operation. This can be useful if
- the port is used with :mod:`select`.
-
- .. method:: fileno()
-
- :platform: Unix
- :return: File descriptor.
-
- Return file descriptor number for the port that is opened by this object.
- It is useful when serial ports are used with :mod:`select`.
-
- .. method:: setXON(level=True)
-
- :platform: Windows
- :param level: Set flow control state.
-
- Set software flow control state.
-
-.. note::
-
- For systems that provide the :py:mod:`io` library (Python 2.6 and newer), the
- class :class:`Serial` will derive from :py:class:`io.RawIOBase`. For all
- others from :class:`FileLike`.
-
-Implementation detail: some attributes and functions are provided by the
-class :class:`SerialBase` and some by the platform specific class and
-others by the base class mentioned above.
-
-.. class:: FileLike
-
- An abstract file like class. It is used as base class for :class:`Serial`
- when no :py:mod:`io` module is available.
-
- This class implements :meth:`readline` and :meth:`readlines` based on
- :meth:`read` and :meth:`writelines` based on :meth:`write`.
-
- Note that when the serial port was opened with no timeout, that
- :meth:`readline` blocks until it sees a newline (or the specified size is
- reached) and that :meth:`readlines` would never return and therefore
- refuses to work (it raises an exception in this case)!
-
- .. method:: writelines(sequence)
-
- Write a list of strings to the port.
-
-
- The following three methods are overridden in :class:`Serial`.
-
- .. method:: flush()
-
- Flush of file like objects. It's a no-op in this class, may be overridden.
-
- .. method:: read()
-
- Raises NotImplementedError, needs to be overridden by subclass.
-
- .. method:: write(data)
-
- Raises NotImplementedError, needs to be overridden by subclass.
-
- The following functions are implemented for compatibility with other
- file-like objects, however serial ports are not seekable.
-
-
- .. method:: seek(pos, whence=0)
-
- :exception IOError: always, as method is not supported on serial port
-
- .. versionadded:: 2.5
-
- .. method:: tell()
-
- :exception IOError: always, as method is not supported on serial port
-
- .. versionadded:: 2.5
-
- .. method:: truncate(self, n=None)
-
- :exception IOError: always, as method is not supported on serial port
-
- .. versionadded:: 2.5
-
- .. method:: isatty()
-
- :exception IOError: always, as method is not supported on serial port
-
- .. versionadded:: 2.5
-
- To be able to use the file like object as iterator for e.g.
- ``for line in Serial(0): ...`` usage:
-
- .. method:: next()
-
- Return the next line by calling :meth:`readline`.
-
- .. method:: __iter__()
-
- Returns self.
-
- Other high level access functions.
-
- .. method:: readline(size=None, eol='\\n')
-
- :param size: Max number of bytes to read, ``None`` -> no limit.
- :param eol: The end of line character.
-
- Read a line which is terminated with end-of-line (*eol*) character
- (``\n`` by default) or until timeout.
-
- .. method:: readlines(sizehint=None, eol='\\n')
-
- :param sizehint: Ignored parameter.
- :param eol: The end of line character.
-
- Read a list of lines, until timeout. *sizehint* is ignored and only
- present for API compatibility with built-in File objects.
-
- Note that this function only returns on a timeout.
-
- .. method:: xreadlines(sizehint=None)
-
- Read lines, implemented as generator. Unlike *readlines* (that only
- returns on a timeout) is this function yielding lines as they are
- received.
-
- .. deprecated:: 2.5
- Use ``for line in Serial(...): ...`` instead. This method is not
- available in Python 2.6 and newer where the :mod:`io` library is
- available and pySerial bases on it.
-
- .. versionchanged:: 2.5
- Implement as generator.
-
-
-:rfc:`2217` Network ports
--------------------------
-
-.. warning:: This implementation is currently in an experimental state. Use
- at your own risk.
-
-.. class:: rfc2217.Serial
-
- This implements a :rfc:`2217` compatible client. Port names are URLs_ in the
- form: ``rfc2217://:[/