Browse Source

Helper now Java Native Library

Thomas Buck 13 years ago
parent
commit
d68c00f373

+ 0
- 15
Cube Control/Frame.java View File

@@ -801,20 +801,6 @@ public class Frame extends JFrame implements ListSelectionListener {
801 801
         System.out.println("All LEDs off now...");
802 802
       }
803 803
 
804
-    if (s.equals("e") || s.equals("exec")) {
805
-          System.out.println(HelperUtility.runHelper(new String[0]));
806
-    }
807
-
808
-    if (s.startsWith("e ") || s.startsWith("exec ")) {
809
-      int pos = 0;
810
-      while (s.charAt(pos) != ' ') {
811
-        pos++;
812
-      }
813
-      String[] arr = new String[1];
814
-      arr[0] = s.substring(pos + 1);
815
-      System.out.println(HelperUtility.runHelper(arr));
816
-    }
817
-
818 804
 	if (s.equals("r") || s.equals("reset")) {
819 805
 		l.resetView();
820 806
 	}
@@ -824,7 +810,6 @@ public class Frame extends JFrame implements ListSelectionListener {
824 810
         System.out.println("\t'on'     / '1'\t:\tToggle all LEDs on");
825 811
         System.out.println("\t'off'    / '0'\t:\tToggle all LEDs off");
826 812
         System.out.println("\t'print'  / 'p'\t:\tPrint 3D Translation Matrix Data");
827
-		System.out.println("\t'exec'   / 'e'\t:\tExecute helper with given args");
828 813
 		System.out.println("\t'reset'  / 'r'\t:\tReset rotation of cube");
829 814
         System.out.println("\t'help'   / 'h'\t:\tShow this message");
830 815
         System.out.println("\t'quit'   / 'q'\t:\tExit Cube Control");

+ 20
- 186
Cube Control/HelperUtility.java View File

@@ -21,27 +21,8 @@
21 21
  * along with LED-Cube.  If not, see <http://www.gnu.org/licenses/>.
22 22
  */
23 23
 
24
-import java.io.File;
25
-import java.io.Closeable;
26
-import java.io.FileNotFoundException;
27
-import java.io.FileOutputStream;
28
-import java.io.IOException;
29
-import java.io.InputStream;
30
-import java.io.InputStreamReader;
31
-import java.io.OutputStream;
32
-import java.io.BufferedReader;
33
-import java.net.URI;
34
-import java.net.URISyntaxException;
35
-import java.net.URL;
36
-import java.security.CodeSource;
37
-import java.security.ProtectionDomain;
38
-import java.util.zip.ZipEntry;
39
-import java.util.zip.ZipException;
40
-import java.util.zip.ZipFile;
41
-import java.lang.Process;
42
-
43 24
 /**
44
- * This helper class extracts the serialHelper from the JAR file, makes it executable and executes it with the given Command line arguments.
25
+ * Helper class which runs our native library.
45 26
  * @author Thomas Buck
46 27
  * @author Max Nuding
47 28
  * @author Felix Bäder
@@ -50,174 +31,27 @@ import java.lang.Process;
50 31
 
51 32
 public class HelperUtility {
52 33
 
53
-	/**
54
-	 * Run the serialHelper with the given arguments
55
-	 * @param args Command line arguments for serialHelper
56
-	 * @return Output of helper
57
-	 */
58
-	public static String runHelper(String[] args) {
59
-		String[] helperName = new String[args.length + 1];
60
-		boolean windows = false;
61
-		if ((System.getProperty("os.name").toLowerCase()).indexOf("win") >= 0) {
62
-			helperName[0] = "serialHelper.exe";
63
-			windows = true;
64
-		} else {
65
-			helperName[0] = "serialHelper";
66
-		}
67
-		for (int i = 0; i < args.length; i++) {
68
-			helperName[i + 1] = args[i];
69
-		}
70
-		String ret = "";
71
-		try {
72
-			File helper = new File(getFile(getJarURI(), helperName[0]));
73
-			helperName[0] = helper.getAbsolutePath();
74
-			if (!windows) {
75
-				Process execute = Runtime.getRuntime().exec("chmod a+x " + helper.getAbsolutePath());
76
-				execute.waitFor();
77
-				if (execute.exitValue() != 0) {
78
-					System.out.println("Could not set helper as executeable (" + execute.exitValue()+ ")");
79
-					return null;
80
-				}
81
-			}
82
-			Process p = Runtime.getRuntime().exec(helperName);
83
-			BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()), 256);
84
-			String line;
85
-			boolean fin;
86
-			
87
-			do {
88
-				fin = true;
89
-				try {
90
-					System.out.println("Returned " + p.waitFor());
91
-				} catch(InterruptedException e) {
92
-					// repeat
93
-					System.out.println("We got interrupted...");
94
-					fin = false;
95
-				}
96
-			} while (fin != true);
97
-
98
-			while ((line = br.readLine()) != null) {
99
-				ret = ret + line + "\n";
100
-			}
101
-
102
-			br.close();
103
-			if (ret.length() > 0) {
104
-				ret = ret.substring(0, ret.length() - 1);
105
-			}
106
-			return ret;
107
-		} catch(Exception e) {
108
-			e.printStackTrace();
109
-		}
110
-
111
-		return null;
34
+	static {
35
+		System.loadLibrary("Serial");
112 36
 	}
113 37
 
114
-	// From http://stackoverflow.com/questions/600146/run-exe-which-is-packaged-inside-jar
115
-	private static URI getJarURI()
116
-        throws URISyntaxException
117
-    {
118
-        final ProtectionDomain domain;
119
-        final CodeSource       source;
120
-        final URL              url;
121
-        final URI              uri;
122
-
123
-        domain = cubeWorker.class.getProtectionDomain();
124
-        source = domain.getCodeSource();
125
-        url    = source.getLocation();
126
-        uri    = url.toURI();
127
-
128
-        return (uri);
129
-    }
130
-
131
-    private static URI getFile(final URI    where,
132
-                               final String fileName)
133
-        throws ZipException,
134
-               IOException
135
-    {
136
-        final File location;
137
-        final URI  fileURI;
138
-
139
-        location = new File(where);
140
-
141
-        // not in a JAR, just return the path on disk
142
-        if(location.isDirectory())
143
-        {
144
-            fileURI = URI.create(where.toString() + fileName);
145
-        }
146
-        else
147
-        {
148
-            final ZipFile zipFile;
149
-
150
-            zipFile = new ZipFile(location);
151
-
152
-            try
153
-            {
154
-                fileURI = extract(zipFile, fileName);
155
-            }
156
-            finally
157
-            {
158
-                zipFile.close();
159
-            }
160
-        }
161
-
162
-        return (fileURI);
163
-    }
164
-
165
-    private static URI extract(final ZipFile zipFile,
166
-                               final String  fileName)
167
-        throws IOException
168
-    {
169
-        final File         tempFile;
170
-        final ZipEntry     entry;
171
-        final InputStream  zipStream;
172
-        OutputStream       fileStream;
173
-
174
-        tempFile = File.createTempFile(fileName, Long.toString(System.currentTimeMillis()));
175
-        tempFile.deleteOnExit();
176
-        entry    = zipFile.getEntry(fileName);
177
-
178
-        if(entry == null)
179
-        {
180
-            throw new FileNotFoundException("cannot find file: " + fileName + " in archive: " + zipFile.getName());
181
-        }
182
-
183
-        zipStream  = zipFile.getInputStream(entry);
184
-        fileStream = null;
185
-
186
-        try
187
-        {
188
-            final byte[] buf;
189
-            int          i;
190
-
191
-            fileStream = new FileOutputStream(tempFile);
192
-            buf        = new byte[1024];
193
-            i          = 0;
194
-
195
-            while((i = zipStream.read(buf)) != -1)
196
-            {
197
-                fileStream.write(buf, 0, i);
198
-            }
199
-        }
200
-        finally
201
-        {
202
-            close(zipStream);
203
-            close(fileStream);
204
-        }
38
+	/**
39
+	 * Get all the existing serial port names
40
+	 * @return List of port names. \n between entries
41
+	 */
42
+	public static native String getPorts();
205 43
 
206
-        return (tempFile.toURI());
207
-    }
44
+	/**
45
+	 * Read data from Cube
46
+	 * @param length Amount of data to read
47
+	 * @return Data read
48
+	 */
49
+	public static native short[] readData(int length);
208 50
 
209
-    private static void close(final Closeable stream)
210
-    {
211
-        if(stream != null)
212
-        {
213
-            try
214
-            {
215
-                stream.close();
216
-            }
217
-            catch(final IOException ex)
218
-            {
219
-                ex.printStackTrace();
220
-            }
221
-        }
222
-    }
51
+	/**
52
+	 * Write data to Cube
53
+	 * @param data Data to write
54
+	 * @param length Length of data
55
+	 */
56
+	public static native void writeData(short[] data, int length);
223 57
 }

+ 1
- 9
Cube Control/cubeWorker.java View File

@@ -381,15 +381,7 @@ public class cubeWorker {
381 381
 	 */
382 382
     public String[] getSerialPorts() {
383 383
 		String[] ports = {"Select serial port..."};
384
-		String helperName;
385
-		if ((System.getProperty("os.name").toLowerCase()).indexOf("win") >= 0) {
386
-			helperName = "serialHelper.exe";
387
-		} else {
388
-			helperName = "serialHelper";
389
-		}
390
-		String[] arg = {"p"};
391
-		String portLines = HelperUtility.runHelper(arg);
392
-		// System.out.println("Output: " + portLines);
384
+		String portLines = HelperUtility.getPorts();
393 385
 		if (portLines == null) {
394 386
 			return ports;
395 387
 		}

+ 1
- 0
Cube Control/helper/unixSerial.c View File

@@ -134,6 +134,7 @@ char** namesInDev(int *siz) {
134 134
 		tmp[3] = 'v';
135 135
 		tmp[4] = '/';
136 136
 		files[i] = strncat(tmp, files[i], strlen(files[i]));
137
+		free(tmp);
137 138
 	}
138 139
 
139 140
 	*siz = size;

+ 25
- 13
Cube Control/makefile View File

@@ -1,20 +1,23 @@
1 1
 JAVAC = javac
2 2
 JAVADOC = javadoc
3
+JAVAH = javah
3 4
 DOCDIR = doc
4 5
 CC = gcc
5
-#TARGET = unix
6
-TARGET= cygwin
6
+TARGET = unix
7
+#TARGET= cygwin
7 8
 #TARGET = win
8 9
 
10
+HEADERPATH = /System/Library/Frameworks/JavaVM.framework/Headers
11
+
9 12
 # Java files to be compiled
10 13
 # Needs to be a complete list so they work as target
11 14
 JAVAFILES = HelperUtility.java AnimationUtility.java Animation.java AFrame.java cubeWorker.java layerEditFrame.java Led3D.java Frame.java
12 15
 
13 16
 ifeq ($(TARGET),unix)
14
-INJAR = *.class *.png serialHelper
15
-RM = rm
17
+INJAR = *.class *.png
18
+RM = rm -f
16 19
 else
17
-INJAR = *.class *.png serialHelper.exe
20
+INJAR = *.class *.png
18 21
 RM = del
19 22
 endif
20 23
 
@@ -26,7 +29,7 @@ RM = rm
26 29
 endif
27 30
 
28 31
 # Spit out jar file, documentation, delete intermediate files
29
-all: build clean
32
+all: build
30 33
 
31 34
 # Generate Documentation
32 35
 doc: doc/index.html
@@ -35,7 +38,7 @@ doc: doc/index.html
35 38
 java: Frame.class
36 39
 
37 40
 # Spit out jar file, dont remove anything after that
38
-build: Frame.class serialHelper
41
+build: Frame.class libSerial
39 42
 	jar -cmf manifest.txt "Cube Control.jar" $(INJAR)
40 43
 
41 44
 # Compile java files
@@ -47,18 +50,27 @@ doc/index.html: $(JAVAFILES)
47 50
 
48 51
 # Compile serial Helper
49 52
 ifeq ($(TARGET),unix)
50
-serialHelper: serialHelper.c helper/unixSerial.c
51
-	$(CC) -o serialHelper serialHelper.c
53
+libSerial: serialInterface.h serialHelper.c helper/unixSerial.c
54
+	$(CC) -x c -I$(HEADERPATH) -c serialHelper.c -o serialHelper.o
55
+	$(CC) -dynamiclib -o libSerial.jnilib serialHelper.o
52 56
 else
53
-serialHelper: serialHelper.c helper/winSerial.c
54
-	$(CC) -o serialHelper.exe -D winHelper serialHelper.c
57
+libSerial: serialInterface.h serialHelper.c helper/winSerial.c
58
+	$(CC) -x c -I$(HEADERPATH) -c serialHelper.c -o serialHelper.o -D winHelper
59
+	$(CC) -dynamiclib -o libSerial.dll serialHelper.o
55 60
 endif
56 61
 
62
+serialInterface.h:
63
+	$(JAVAC) HelperUtility.java
64
+	$(JAVAH) -o serialInterface.h HelperUtility
65
+
57 66
 # Delete intermediate files
58 67
 clean:
59 68
 	$(RM) *.class
69
+	$(RM) *.h
70
+	$(RM) *.o
71
+	$(RM) *.jar
60 72
 ifeq ($(TARGET),unix)
61
-	$(RM) serialHelper
73
+	$(RM) *.jnilib
62 74
 else
63
-	$(RM) serialHelper.exe
75
+	$(RM) *.dll
64 76
 endif

+ 30
- 186
Cube Control/serialHelper.c View File

@@ -22,6 +22,8 @@
22 22
  */
23 23
 #include <stdlib.h>
24 24
 #include <stdio.h>
25
+#include <jni.h>
26
+#include "serialInterface.h"
25 27
 
26 28
 #ifdef winHelper
27 29
 #include "helper/winSerial.c"
@@ -29,200 +31,42 @@
29 31
 #include "helper/unixSerial.c"
30 32
 #endif
31 33
 
32
-char *fileData = NULL;
33
-
34
-void removeFromBeginning(size_t size, size_t remove);
35
-size_t readFile(char *path);
36
-size_t getFileSize(FILE *fp);
37
-void usage(char *name);
38
-int parseNumber(char *s);
39
-int power(int num, int pow);
40
-void printFileData(size_t size);
41
-void printSerialPorts(char ** ports);
42
-
43
-/*
44
-Return values:
45
-0: Success
46
-1: Usage error
47
-2: Serial Port Error
48
-3: Data File Error
49
-*/
50
-
51
-int main(int argc, char *argv[]) {
52
-	size_t length, written;
53
-
54
-		// printf("Debugging Worker... Ignore me!\n");
55
-
56
-		if (argc < 2) {
57
-			usage(argv[0]);
58
-			return 1;
34
+JNIEXPORT jstring JNICALL Java_HelperUtility_getPorts(JNIEnv *env, jclass class) {
35
+	char **ports = getSerialPorts();
36
+	char *string = NULL;
37
+	int length = 0, leng2 = 0, lengthabs = 0;;
38
+	while (ports[length] != NULL) {
39
+		while (ports[length][leng2] != '\0') {
40
+			leng2++;
59 41
 		}
60
-
61
-		if (argv[1][0] == 'p') {
62
-
63
-			if (argc != 2) {
64
-				usage(argv[0]);
65
-				return 1;
66
-			}
67
-			char** ports = getSerialPorts();
68
-			printSerialPorts(ports);
69
-			free(ports);
70
-			return 0;
71
-
72
-		} else if (argv[1][0] == 'w') {
73
-
74
-			if (argc != 4) {
75
-				usage(argv[0]);
76
-				return 1;
77
-			}
78
-			if (serialOpen(argv[2]) != 0) {
79
-				printf("Error: Could not open %s\n", argv[1]);
80
-				return 2;
81
-			}
82
-			// write file to com port
83
-			length = readFile(argv[3]);
84
-			if (length == 0) {
85
-				printf("Error while reading %s\n", argv[2]);
86
-				return 3;
87
-			}
88
-	
89
-			written = serialWrite(fileData, length);
90
-			while (written < length) {
91
-				removeFromBeginning(length, written);
92
-				length -= written;
93
-				written = serialWrite(fileData, length);
94
-			}
95
-
96
-		} else if (argv[1][0] == 'r') {
97
-
98
-			if (argc != 4) {
99
-				usage(argv[0]);
100
-				return 1;
101
-			}
102
-			if (serialOpen(argv[2]) != 0) {
103
-				printf("Error: Could not open %s\n", argv[1]);
104
-				return 2;
105
-			}
106
-			// Read from com port to file
107
-			if (argc < 5) {
108
-				printf("No size given. ");
109
-				usage(argv[0]);
110
-				return 1;
111
-			}
112
-			
113
-			length = parseNumber(argv[3]);
114
-			fileData = (char *)malloc(length * sizeof(char));
115
-			// fill fileData with serial Port data
116
-			written = 0;
117
-			while (written < length) {
118
-				written = serialRead(fileData + written, length - written);
119
-			}
120
-
121
-			printFileData(length);
122
-
123
-		} else {
124
-			printf("Unrecognized Option: %s\n", argv[1]);
125
-			usage(argv[0]);
126
-			return 1;
127
-		}
128
-
129
-		free(fileData);
130
-		fileData = NULL;
131
-		serialClose();
132
-		return 0;
133
-	// }
134
-}
135
-
136
-void removeFromBeginning(size_t size, size_t remove) {
137
-	size_t i;
138
-	char *tmp = (char *)malloc((size - remove) * sizeof(char));
139
-
140
-	for (i = 0; i < (size - remove); i++) {
141
-		tmp[i] = fileData[i + remove];
142
-	}
143
-	free(fileData);
144
-	fileData = tmp;
145
-}
146
-
147
-size_t readFile(char *path) {
148
-	size_t size, i;
149
-	FILE *fp;
150
-
151
-	fp = fopen(path, "r");
152
-	if (!fp) {
153
-		return 0;
154
-	}
155
-
156
-	size = getFileSize(fp);
157
-	fileData = (char *)malloc(size * sizeof(char));
158
-	for (i = 0; i < size; i++) {
159
-		fileData[i] = fgetc(fp);
42
+		lengthabs += leng2;
43
+		leng2 = 0;
44
+		length++;
160 45
 	}
161
-
162
-	fclose(fp);
163
-	return size;
164
-}
165
-
166
-size_t getFileSize(FILE *fp) {
167
-	size_t size = 0;
168
-	int c;
169
-
170
-	fseek(fp, 0, 0); // Set file pointer to beginning
171 46
 	
172
-	do { // Calculate size
173
-		c = fgetc(fp);
174
-		size++;
175
-	} while (c != EOF);
176
-	size--;
47
+	length += lengthabs;
48
+	string = (char *)malloc((length * sizeof(char)) + 1);
177 49
 	
178
-	fseek(fp, 0, 0);
179
-
180
-	return size;
181
-}
182
-
183
-void usage(char *name) {
184
-#ifdef winHelper
185
-	printf("Usage:\n%s r|w|p [COM1 [C:\\file\\to\\send.txt] [sizeToRead]]\n", name);
186
-#else
187
-	printf("Usage:\n%s r|w|p [/dev/SerialPort [/file/to/send] [sizeToRead]]\n", name);
188
-#endif
189
-}
190
-
191
-int parseNumber(char *s) {
192
-	int i, size = 0, result = 0;
193
-	while (*(s++) != '\0') {
194
-		size++;
195
-	}
196
-	for (i = 0; i < size; i++) {
197
-		result += (s[i] - '0') * power(10, (size - i));
50
+	length = 0;
51
+	lengthabs = 0;
52
+	while (ports[length] != NULL) {
53
+		leng2 = 0;
54
+		while (ports[length][leng2] != '\0') {
55
+			string[lengthabs++] = ports[length][leng2++];
56
+		}
57
+		string[lengthabs++] = '\n';
58
+		length++;
198 59
 	}
199
-	return result;
200
-}
60
+	string[lengthabs] = '\0';
201 61
 
202
-int power(int num, int pow) {
203
-	int result = 1;
204
-	while (pow > 0) {
205
-		result *= num;
206
-		pow--;
207
-	}
208
-	return result;
62
+	jstring ret = (*env)->NewStringUTF(env, string);
63
+	return ret;
209 64
 }
210 65
 
211
-void printFileData(size_t size) {
212
-	int i;
213
-	for (i = 0; i < size; i++) {
214
-		printf("%x", fileData[i]);
215
-		if (i % 8 == 0) {
216
-			printf("\n");
217
-		}
218
-	}
66
+JNIEXPORT jshortArray JNICALL Java_HelperUtility_readData(JNIEnv *env, jclass class, jint length) {
67
+	return NULL;
219 68
 }
220 69
 
221
-void printSerialPorts(char ** ports) {
222
-	int i = 0;
223
-	while (ports[i] != NULL) {
224
-		printf("%s\n", ports[i]);
225
-		i++;
226
-	}
70
+JNIEXPORT void JNICALL Java_HelperUtility_writeData(JNIEnv *env, jclass class, jshortArray data, jint length) {
71
+	return;
227 72
 }
228
-

Loading…
Cancel
Save