1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
|
JNIEXPORT jobject JNICALL Java_com_crow_modbus_serialport_SerialPort_open (JNIEnv *env, jclass thiz, jstring path, jint baudrate, jint flags, jint parity, jint stop_bit, jint data_bit) { LOGD("----------------------------------------------------------"); int fd; speed_t speed; jobject mFileDescriptor;
{ speed = getBaudrate(baudrate); if (speed == -1) { LOGE("Invalid baudrate!"); return NULL; } }
{ jboolean iscopy; const char *path_utf = (*env)->GetStringUTFChars(env, path, &iscopy); LOGD("Opening serial port %s with flags 0x%x", path_utf, O_RDWR | flags); fd = open(path_utf, O_RDWR | flags); LOGD("open() fd = %d", fd); (*env)->ReleaseStringUTFChars(env, path, path_utf); if (fd == -1) { LOGE("Cannot open port"); return NULL; } }
{ struct termios cfg; LOGD("Configuring serial port"); if (tcgetattr(fd, &cfg)) { LOGE("tcgetattr() failed"); close(fd); return NULL; }
cfmakeraw(&cfg);
cfsetispeed(&cfg, speed); cfsetospeed(&cfg, speed);
cfg.c_cflag &= ~CSIZE; switch (data_bit) { case 5: cfg.c_cflag |= CS5; break; case 6: cfg.c_cflag |= CS6; break; case 7: cfg.c_cflag |= CS7; break; case 8: default: cfg.c_cflag |= CS8; break; }
if (stop_bit == 1) cfg.c_cflag &= ~CSTOPB; else cfg.c_cflag |= CSTOPB;
if (parity == 0) { LOGD("NONE"); cfg.c_cflag &= ~PARENB; } else if (parity == 1) { LOGD("Even"); cfg.c_cflag |= PARENB; cfg.c_cflag &= ~PARODD; } else { LOGD("ODD"); cfg.c_cflag |= PARENB; cfg.c_cflag |= PARODD; } if (tcsetattr(fd, TCSANOW, &cfg)) { LOGE("tcsetattr() failed"); close(fd); return NULL; } }
{ jclass cFileDescriptor = (*env)->FindClass(env, "java/io/FileDescriptor"); jmethodID iFileDescriptor = (*env)->GetMethodID(env, cFileDescriptor, "<init>", "()V"); jfieldID descriptorID = (*env)->GetFieldID(env, cFileDescriptor, "descriptor", "I"); mFileDescriptor = (*env)->NewObject(env, cFileDescriptor, iFileDescriptor); (*env)->SetIntField(env, mFileDescriptor, descriptorID, (jint) fd); }
return mFileDescriptor; }
|