Commit 8f22acbe authored by pengguangpu's avatar pengguangpu

扩散jar包代码,完善weighing moudle

parent 5c645801
...@@ -4,6 +4,20 @@ ...@@ -4,6 +4,20 @@
android:layout_height="match_parent" android:layout_height="match_parent"
android:orientation="vertical"> android:orientation="vertical">
<android.support.v7.widget.ActionMenuView
android:layout_width="match_parent"
android:layout_height="88dp"
android:background="@color/colorPrimary">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="米雅硬件开放平台"
android:textColor="#ffffff"
android:textSize="36sp" />
</android.support.v7.widget.ActionMenuView>
<Button <Button
android:id="@+id/btnWeighing" android:id="@+id/btnWeighing"
android:layout_width="match_parent" android:layout_width="match_parent"
......
...@@ -4,6 +4,20 @@ ...@@ -4,6 +4,20 @@
android:layout_height="match_parent" android:layout_height="match_parent"
android:orientation="vertical"> android:orientation="vertical">
<android.support.v7.widget.ActionMenuView
android:layout_width="match_parent"
android:layout_height="88dp"
android:background="@color/colorPrimary">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="称重开放平台"
android:textColor="#ffffff"
android:textSize="36sp" />
</android.support.v7.widget.ActionMenuView>
<TextView <TextView
android:id="@+id/tvResult" android:id="@+id/tvResult"
android:layout_width="wrap_content" android:layout_width="wrap_content"
......
<resources> <resources>
<string name="app_name">hardware</string> <string name="app_name">米雅硬件开放平台</string>
</resources> </resources>
<resources> <resources>
<!-- Base application theme. --> <!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. --> <!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
......
# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html
# Sets the minimum version of CMake required to build the native library.
cmake_minimum_required(VERSION 3.4.1)
# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.
add_library( # Sets the name of the library.
SerialPort
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
src/main/cpp/SerialPort.c )
# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.
find_library( # Sets the name of the path variable.
log-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
log )
# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.
target_link_libraries( # Specifies the target library.
SerialPort
# Links the target library to the log library
# included in the NDK.
${log-lib} )
\ No newline at end of file
...@@ -41,7 +41,7 @@ dependencies { ...@@ -41,7 +41,7 @@ dependencies {
//商米称重驱动 //商米称重驱动
implementation files('libs/scale-service-part-lib-1.1.jar') implementation files('libs/scale-service-part-lib-1.1.jar')
//创捷称重驱动jar包(自制) //创捷称重驱动jar包(自制)
implementation files('libs/chuangjieweighing.jar') // implementation files('libs/chuangjieweighing.jar')
//映泰机器称重驱动jar包(自制) //映泰机器称重驱动jar包(自制)
implementation files('libs/yingtaiweighing.jar') // implementation files('libs/yingtaiweighing.jar')
} }
/*
* Copyright 2009-2011 Cedric Priscal
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <termios.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <jni.h>
#include "android_serialport_api_SerialPort.h"
#include "android/log.h"
static const char *TAG="serial_port";
#define LOGI(fmt, args...) __android_log_print(ANDROID_LOG_INFO, TAG, fmt, ##args)
#define LOGD(fmt, args...) __android_log_print(ANDROID_LOG_DEBUG, TAG, fmt, ##args)
#define LOGE(fmt, args...) __android_log_print(ANDROID_LOG_ERROR, TAG, fmt, ##args)
static speed_t getBaudrate(jint baudrate)
{
switch(baudrate) {
case 0: return B0;
case 50: return B50;
case 75: return B75;
case 110: return B110;
case 134: return B134;
case 150: return B150;
case 200: return B200;
case 300: return B300;
case 600: return B600;
case 1200: return B1200;
case 1800: return B1800;
case 2400: return B2400;
case 4800: return B4800;
case 9600: return B9600;
case 19200: return B19200;
case 38400: return B38400;
case 57600: return B57600;
case 115200: return B115200;
case 230400: return B230400;
case 460800: return B460800;
case 500000: return B500000;
case 576000: return B576000;
case 921600: return B921600;
case 1000000: return B1000000;
case 1152000: return B1152000;
case 1500000: return B1500000;
case 2000000: return B2000000;
case 2500000: return B2500000;
case 3000000: return B3000000;
case 3500000: return B3500000;
case 4000000: return B4000000;
default: return -1;
}
}
/*
* Class: android_serialport_SerialPort
* Method: open
* Signature: (Ljava/lang/String;II)Ljava/io/FileDescriptor;
*/
JNIEXPORT jobject JNICALL Java_android_1serialport_1api_SerialPort1_open
(JNIEnv *env, jclass thiz, jstring path, jint baudrate, jint flags)
{
int fd;
speed_t speed;
jobject mFileDescriptor;
/* Check arguments */
{
speed = getBaudrate(baudrate);
if (speed == -1) {
/* TODO: throw an exception */
LOGE("Invalid baudrate");
return NULL;
}
}
/* Opening device */
{
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)
{
/* Throw an exception */
LOGE("Cannot open port");
/* TODO: throw an exception */
return NULL;
}
}
/* Configure device */
{
struct termios cfg;
LOGD("Configuring serial port");
if (tcgetattr(fd, &cfg))
{
LOGE("tcgetattr() failed");
close(fd);
/* TODO: throw an exception */
return NULL;
}
cfmakeraw(&cfg);
cfsetispeed(&cfg, speed);
cfsetospeed(&cfg, speed);
if (tcsetattr(fd, TCSANOW, &cfg))
{
LOGE("tcsetattr() failed");
close(fd);
/* TODO: throw an exception */
return NULL;
}
}
/* Create a corresponding file descriptor */
{
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;
}
/*
* Class: cedric_serial_SerialPort
* Method: close
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_android_1serialport_1api_SerialPort1_close
(JNIEnv *env, jobject thiz)
{
jclass SerialPortClass = (*env)->GetObjectClass(env, thiz);
jclass FileDescriptorClass = (*env)->FindClass(env, "java/io/FileDescriptor");
jfieldID mFdID = (*env)->GetFieldID(env, SerialPortClass, "mFd", "Ljava/io/FileDescriptor;");
jfieldID descriptorID = (*env)->GetFieldID(env, FileDescriptorClass, "descriptor", "I");
jobject mFd = (*env)->GetObjectField(env, thiz, mFdID);
jint descriptor = (*env)->GetIntField(env, mFd, descriptorID);
LOGD("close(fd = %d)", descriptor);
close(descriptor);
}
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class android_serialport_api_SerialPort */
#ifndef _Included_android_serialport_api_SerialPort
#define _Included_android_serialport_api_SerialPort
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: android_serialport_api_SerialPort
* Method: open
* Signature: (Ljava/lang/String;II)Ljava/io/FileDescriptor;
*/
JNIEXPORT jobject JNICALL Java_android_1serialport_1api_SerialPort1_open
(JNIEnv *, jclass, jstring, jint, jint);
/*
* Class: android_serialport_api_SerialPort
* Method: close
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_android_1serialport_1api_SerialPort1_close
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
/*
* Copyright 2009 Cedric Priscal
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android_serialport_api;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Scanner;
import android.util.Log;
public class SerialPort1 {
private static final String TAG = "SerialPort1";
/*
* Do not remove or rename the field mFd: it is used by native method close();
*/
private FileDescriptor mFd;
private FileInputStream mFileInputStream;
private FileOutputStream mFileOutputStream;
public SerialPort1(File device, int baudrate, int flags) throws SecurityException, IOException {
/* Check access permission */
if (!device.canRead() || !device.canWrite()) {
try {
/* Missing read/write permission, trying to chmod the file */
Process su;
su = Runtime.getRuntime().exec("/system/xbin/su");
String cmd = "chmod 666 " + device.getAbsolutePath() + "\n"
+ "exit\n";
su.getOutputStream().write(cmd.getBytes());
System.out.println(">>>>>>>");
int re=su.waitFor();
System.out.println("<<<<<<<<<");
if ( re!= 0 || !device.canRead()
|| !device.canWrite()) {
throw new SecurityException();
}
} catch (Exception e) {
e.printStackTrace();
throw new SecurityException();
}
}
mFd = open(device.getAbsolutePath(), baudrate, flags);
if (mFd == null) {
Log.e(TAG, "native open returns null");
throw new IOException();
}
mFileInputStream = new FileInputStream(mFd);
mFileOutputStream = new FileOutputStream(mFd);
}
// Getters and setters
public InputStream getInputStream() {
return mFileInputStream;
}
public OutputStream getOutputStream() {
return mFileOutputStream;
}
// JNI
private native static FileDescriptor open(String path, int baudrate, int flags);
public native void close();
static {
System.loadLibrary("SerialPort");
}
}
/*
* Copyright 2009 Cedric Priscal
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android_serialport_api;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.Iterator;
import java.util.Vector;
import android.util.Log;
public class SerialPortFinder {
public class Driver {
public Driver(String name, String root) {
mDriverName = name;
mDeviceRoot = root;
}
private String mDriverName;
private String mDeviceRoot;
Vector<File> mDevices = null;
public Vector<File> getDevices() {
if (mDevices == null) {
mDevices = new Vector<File>();
File dev = new File("/dev");
File[] files = dev.listFiles();
int i;
for (i=0; i<files.length; i++) {
if (files[i].getAbsolutePath().startsWith(mDeviceRoot)) {
Log.d(TAG, "Found new device: " + files[i]);
mDevices.add(files[i]);
}
}
}
return mDevices;
}
public String getName() {
return mDriverName;
}
}
private static final String TAG = "SerialPort1";
private Vector<Driver> mDrivers = null;
Vector<Driver> getDrivers() throws IOException {
if (mDrivers == null) {
mDrivers = new Vector<Driver>();
LineNumberReader r = new LineNumberReader(new FileReader("/proc/tty/drivers"));
String l;
while((l = r.readLine()) != null) {
// Issue 3:
// Since driver name may contain spaces, we do not extract driver name with split()
String drivername = l.substring(0, 0x15).trim();
String[] w = l.split(" +");
if ((w.length >= 5) && (w[w.length-1].equals("serial"))) {
Log.d(TAG, "Found new driver " + drivername + " on " + w[w.length-4]);
mDrivers.add(new Driver(drivername, w[w.length-4]));
}
}
r.close();
}
return mDrivers;
}
public String[] getAllDevices() {
Vector<String> devices = new Vector<String>();
// Parse each driver
Iterator<Driver> itdriv;
try {
itdriv = getDrivers().iterator();
while(itdriv.hasNext()) {
Driver driver = itdriv.next();
Iterator<File> itdev = driver.getDevices().iterator();
while(itdev.hasNext()) {
String device = itdev.next().getName();
String value = String.format("%s (%s)", device, driver.getName());
devices.add(value);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return devices.toArray(new String[devices.size()]);
}
public String[] getAllDevicesPath() {
Vector<String> devices = new Vector<String>();
// Parse each driver
Iterator<Driver> itdriv;
try {
itdriv = getDrivers().iterator();
while(itdriv.hasNext()) {
Driver driver = itdriv.next();
Iterator<File> itdev = driver.getDevices().iterator();
while(itdev.hasNext()) {
String device = itdev.next().getAbsolutePath();
devices.add(device);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return devices.toArray(new String[devices.size()]);
}
}
package cn.wintec.wtandroidjar;
import android.os.Build;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ComIO {
private String devicePath;
private int[] readHandle;
private int[] readHandle2;
private Lock lock;
/**
* Constructor
*
* @param devicePath UART device path,for example�?/dev/ttymxc1
*/
public ComIO(String devicePath) {
this.devicePath = devicePath;
this.readHandle = new int[4];
this.readHandle[0] = -1;
this.readHandle[1] = -1;
this.readHandle[2] = -1;
this.readHandle[3] = 0;
this.readHandle2 = new int[4];
this.lock = new ReentrantLock();
}
/**
* Write data to the uart
*
* @param string the string need to write to uart
* @throws IOException
*/
public void write(String string) throws IOException {
File file = new File(devicePath);
FileOutputStream stream = new FileOutputStream(file);
try {
stream.write(string.getBytes());
} finally {
stream.flush();
stream.close();
}
}
/**
* Write buffer contents to the UART
*
* @param buffer The data needs to be written to the uart
* @throws IOException
*/
public void write(byte[] buffer)
throws IOException {
File file = new File(devicePath);
FileOutputStream stream = new FileOutputStream(file);
try {
stream.write(buffer);
} finally {
stream.flush();
stream.close();
}
}
/**
* read data from the uart
*
* @param buffer the buffer of store read data
* @param offset the start position data stored in the buffer
* @param length Maximum read length
* @return The actual number of bytes read. If the device does not exist, returns -1
* @throws IOException
*/
public int read(byte[] buffer, int offset, int length) {
lock.lock();
startReadFile(devicePath, readHandle);
readHandle2[0] = readHandle[0];
readHandle2[1] = readHandle[1];
readHandle2[2] = readHandle[2];
readHandle2[3] = readHandle[3];
lock.unlock();
int ret = readFile(readHandle2, buffer, offset, length, -1);
return ret;
}
/**
* read data from the uart,overtime
*
* @param buffer the buffer of store read data
* @param offset the start position data stored in the buffer
* @param length Maximum read length
* @param millisecond timeout
* @return The actual number of bytes read. If the device does not exist, returns -1
*/
public int read(byte[] buffer, int offset, int length, long millisecond) {
lock.lock();
startReadFile(devicePath, readHandle);
readHandle2[0] = readHandle[0];
readHandle2[1] = readHandle[1];
readHandle2[2] = readHandle[2];
readHandle2[3] = readHandle[3];
lock.unlock();
//Log.v("Read3", String.format("beginx %d", readHandle2[0]));
int lenRemain = length;
int ret = 0;
int length1 = offset;
boolean dataReceived = false;
long beginReadTime = System.currentTimeMillis();
while (true) {
if (lenRemain > 10) {
ret = readFile(readHandle2, buffer, length1, 10, 5);
} else {
ret = readFile(readHandle2, buffer, length1, lenRemain, 5);
}
lenRemain -= ret;
if (ret > 0)//ԭ����!=0�޸�Ϊ����0
dataReceived = true;
if (!dataReceived) {
long usedTime = System.currentTimeMillis() - beginReadTime;
if (usedTime > millisecond) {
return 0;
}
}
length1 += ret;
if (dataReceived && ret < 10)
break;
}
// Log.v("Read", "over");
return length1 - offset;
}
/**
* If an object is called off ComIO read function, be sure to call this function recovery resources;
* This function also cancel're reading read function
*/
public void readFinish() {
lock.lock();
stopReadFile(readHandle);
lock.unlock();
}
public enum Baudrate {
BAUD_115200, BAUD_57600,
BAUD_38400, BAUD_19200, BAUD_9600, BAUD_4800,
BAUD_2400, BAUD_1200, BAUD_600, BAUD_300,
BAUD_UNKNOWN,
}
public enum VerifyBit {
NONE, ODD, EVEN,
}
public enum DataBit {
DATA_BIT_8,
DATA_BIT_7,
DATA_BIT_6,
DATA_BIT_5,
}
public enum StopBit {
STOP_BIT_1,
STOP_BIT_2
}
public enum FlowControl {
NONE, RTS_CTS, DTR_DSR,
}
public class Param {
public Baudrate baudrate;
public VerifyBit verifyBit;
public DataBit dataBit;
public StopBit stopBit;
public FlowControl flowControl;
}
;
/**
* set UART parameter
*
* @param baudrate
* @param verifyBit
* @param dataBit
* @param stopBit
* @param flowControl
*/
public void setSerialParam(
Baudrate baudrate,
VerifyBit verifyBit,
DataBit dataBit,
StopBit stopBit,
FlowControl flowControl) {
String verifyBit_ = verifyBit.toString();
String baudrate_ = baudrate.toString().substring(9);
String dataBit_ = "cs" + dataBit.toString().substring(9);
String stopBit_ = dataBit.toString();
if (verifyBit == VerifyBit.NONE) verifyBit_ = "-parenb";
else if (verifyBit == VerifyBit.ODD) verifyBit_ = "parodd";
else if (verifyBit == VerifyBit.EVEN) verifyBit_ = "_parodd";
if (stopBit == StopBit.STOP_BIT_1) stopBit_ = "-cstopb";
else if (stopBit == StopBit.STOP_BIT_2) stopBit_ = "cstopb";
String pathpredix = "busybox stty -F ";
String pathsuffix = devicePath + " " + baudrate_ + " " + verifyBit_ + " " + dataBit_ + " " + stopBit_;
String cmd = pathpredix.concat(pathsuffix);
try {
Process setSerialParam = Runtime.getRuntime().exec(cmd);
setSerialParam.waitFor();
System.out.println("yeah!");
} catch (IOException e) {
System.out.println(cmd);
} catch (InterruptedException e) {
}
}
public void enableRTS_CTS() {
String cmd = "busybox stty -F " + devicePath + " xonxoff";
// String cmd = "busybox stty -F " + devicePath + " crtscts";
try {
Process setSerialParam = Runtime.getRuntime().exec(cmd);
setSerialParam.waitFor();
System.out.println("yeah!");
} catch (IOException e) {
System.out.println(cmd);
} catch (InterruptedException e) {
}
}
public void disableRTS_CTS() {
String cmd = "busybox stty -F " + devicePath + " -xonxoff";
// String cmd = "busybox stty -F " + devicePath + " -crtscts";
try {
Process setSerialParam = Runtime.getRuntime().exec(cmd);
setSerialParam.waitFor();
System.out.println("yeah!");
} catch (IOException e) {
System.out.println(cmd);
} catch (InterruptedException e) {
}
}
/**
* get UART parameter
*
* @return collection of UART parameter
*/
public Param getSerialParam() {
Param param = new Param();
param.baudrate = Baudrate.BAUD_115200;
param.verifyBit = VerifyBit.NONE;
param.dataBit = DataBit.DATA_BIT_8;
param.stopBit = StopBit.STOP_BIT_1;
param.flowControl = FlowControl.NONE;
String cmd = "busybox stty -F " + devicePath + " -a";
StringBuffer content = new StringBuffer();
try {
Process setSerialParam = Runtime.getRuntime().exec(cmd);
InputStream comExeResult = setSerialParam.getInputStream();
int temp;
while ((temp = comExeResult.read()) != -1) {
if ((char) temp == ';') {
content.append(" ");
} else {
content.append((char) temp);
}
}
String comParameters = content.toString();
String baudrate, dataBit;
boolean verify, verifyBit;
Pattern p1 = Pattern.compile("(\\r|\\n|.)*speed\\s+(300|600|1200|2400|4800|9600|19200|" +
"38400|43000|56000|57600|115200)\\b(\\r|\\n|.)*");
Matcher m1 = p1.matcher(comParameters);
m1.matches();
baudrate = m1.group(2);
if (baudrate.equals("300")) param.baudrate = Baudrate.BAUD_300;
else if (baudrate.equals("600")) param.baudrate = Baudrate.BAUD_600;
else if (baudrate.equals("1200")) param.baudrate = Baudrate.BAUD_1200;
else if (baudrate.equals("2400")) param.baudrate = Baudrate.BAUD_2400;
else if (baudrate.equals("4800")) param.baudrate = Baudrate.BAUD_4800;
else if (baudrate.equals("9600")) param.baudrate = Baudrate.BAUD_9600;
else if (baudrate.equals("19200")) param.baudrate = Baudrate.BAUD_19200;
else if (baudrate.equals("38400")) param.baudrate = Baudrate.BAUD_38400;
else if (baudrate.equals("57600")) param.baudrate = Baudrate.BAUD_57600;
else if (baudrate.equals("115200")) param.baudrate = Baudrate.BAUD_115200;
Pattern p2 = Pattern.compile("(\r|\n|.)*(-parenb)(\r|\n|.)*");
Matcher m2 = p2.matcher(comParameters);
verify = m2.matches();
Pattern p3 = Pattern.compile("(\r|\n|.)*(-parodd)(\r|\n|.)*");
Matcher m3 = p3.matcher(comParameters);
verifyBit = m3.matches();
if (verify) param.verifyBit = VerifyBit.NONE;
else if (verify == false && verifyBit == true) param.verifyBit = VerifyBit.EVEN;
else if (verify == false && verifyBit == false) param.verifyBit = VerifyBit.ODD;
Pattern p4 = Pattern.compile("(\r|\n|.)*(-cstopb)(\r|\n|.)*");
Matcher m4 = p4.matcher(comParameters);
if (m4.matches()) param.stopBit = StopBit.STOP_BIT_1;
else param.stopBit = StopBit.STOP_BIT_2;
Pattern p5 = Pattern.compile("(\r|\n|.)*(-ixon)(\r|\n|.)*");
Matcher m5 = p5.matcher(comParameters);
if (m5.matches()) param.flowControl = FlowControl.NONE;
else param.flowControl = FlowControl.DTR_DSR;
Pattern p6 = Pattern.compile("(\r|\n|.)*(cs5|cs6|cs7|cs8)(\r|\n|.)*");
Matcher m6 = p6.matcher(comParameters);
m6.matches();
dataBit = m6.group(2);
if (dataBit.equals("cs8")) param.dataBit = DataBit.DATA_BIT_8;
else if (dataBit.equals("cs7")) param.dataBit = DataBit.DATA_BIT_7;
else if (dataBit.equals("cs6")) param.dataBit = DataBit.DATA_BIT_6;
else if (dataBit.equals("cs5")) param.dataBit = DataBit.DATA_BIT_5;
//Log.d("默认参数已取�?,"GetCurrentSystemParameters");
} catch (IOException e) {
System.out.println(cmd + e.toString());
}
return param;
}
/**
* get baudrate of UART
*
* @return baudrate of UART
*/
public Baudrate getSerialBaudrate() {
int value = tcgetattr(devicePath);
switch (value) {
case 115200:
return Baudrate.BAUD_115200;
case 57600:
return Baudrate.BAUD_57600;
case 38400:
return Baudrate.BAUD_38400;
case 19200:
return Baudrate.BAUD_19200;
case 9600:
return Baudrate.BAUD_9600;
case 4800:
return Baudrate.BAUD_4800;
case 2400:
return Baudrate.BAUD_2400;
case 1200:
return Baudrate.BAUD_1200;
case 600:
return Baudrate.BAUD_600;
case 300:
return Baudrate.BAUD_300;
default:
return Baudrate.BAUD_UNKNOWN;
}
}
/**
* set baudrate of UART
*
* @param baudrate
*/
public void setSerialBaudrate(Baudrate baudrate) {
int value;
switch (baudrate) {
case BAUD_115200:
value = 115200;
break;
case BAUD_57600:
value = 57600;
break;
case BAUD_38400:
value = 38400;
break;
case BAUD_19200:
value = 19200;
break;
case BAUD_9600:
value = 9600;
break;
case BAUD_4800:
value = 4800;
break;
case BAUD_2400:
value = 2400;
break;
case BAUD_1200:
value = 1200;
break;
case BAUD_600:
value = 600;
break;
case BAUD_300:
value = 300;
break;
default:
return;
}
tcsetattr(devicePath, value);
}
/**
* set baudrate of UART
*
* @param baudrate
*/
public void setSerialBaudrate(int baudrate) {
tcsetattr(devicePath, baudrate);
}
public void clearBuffer() {
tcflush(devicePath);
}
private native void startReadFile(String path, int[] fds);
private native void stopReadFile(int[] fds);
private native int readFile(int[] fds, byte[] buffer, int offset, int length, long millisecond);
private native int tcsetattr(String path, int baudrate);
private native int tcgetattr(String path);
private native void tcflush(String path);
static {
if (isArm()) {
System.loadLibrary("jni");
}
}
/**
* 获取cpu支持的架构类型
*
* @return 支持的架构字符串
*/
public static List<String> getCpuSupportAbis() {
String[] abis;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
abis = Build.SUPPORTED_ABIS;
} else {
abis = new String[]{Build.CPU_ABI, Build.CPU_ABI2};
}
List<String> list = new ArrayList<>();
for (String tmp : abis) {
list.add(tmp);
}
return list;
}
/**
* 是否是arm架构
*
* @return
*/
public static boolean isArm() {
boolean isArm = false;
for (String tmp : getCpuSupportAbis()) {
if (tmp.contains("armeabi")) {
//是arm架构
isArm = true;
break;
}
}
return isArm;
}
}
\ No newline at end of file
package cn.wintec.wtandroidjar;
import java.io.IOException;
import java.text.DecimalFormat;
import android.util.Log;
public class SCL {
private ComIO comio;
public SCL(String devicePath) {
// comio = new ComIO("/dev/ttySAC0");//3
comio = new ComIO(devicePath);
comio.setSerialBaudrate(9600);
// 打开流控
}
public SCL(String devicePath, ComIO.Baudrate baudrate) {
comio = new ComIO(devicePath);
comio.setSerialBaudrate(baudrate);
// 打开流控
}
private boolean OutPutSerialPort(String bytes) {
try {
comio.write(bytes.getBytes("ASCII"));
return true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
public void PAUSE() {
OutPutSerialPort("PAUSE\r\n");
}
public void RESUME() {
OutPutSerialPort("RESUME\r\n");
}
public String ASCII2HexString(byte[] src, int n) {
char[] data = new char[n];
for (int i = 0; i < src.length; i++) {
data[i] = (char) ((int) (src[i]));
}
return new String(data);
}
public byte[] ReadData() {
byte[] line = new byte[22];
int index = 0;
byte[] content = new byte[2];
for (; ; ) {
if (comio.read(content, 0, 1, 100) != 0) {
line[index] = content[0];
index++;
if (index >= 22) // 防止读取超出地址
{
break;
}
if (content[0] == 10)// read end
{
break;
}
} else {
// WGT:3 0.000P 0.000\r\n
line[0] = 'E';
for (int i = 1; i < 22; i++) {
line[i] = 0;
}
return line;
}
}
return line;
}
/**
* 打印byte数组
*/
String printByte(byte[] byteData) {
Log.i("pupu原始数据", "byteData length==>" + byteData.length);
String result = "";
for (int i = 0; i < byteData.length; i++) {
Log.i("pupu原始数据", "byteData[i]==>" + Integer.toBinaryString(((int) byteData[i])));
result = result + byteData[i];
}
return result;
}
/**
* 标准读取
*
* @param buf
* @return 标志位(1个字节)+净重(6个字节)+P+皮重(6个字节)
*/
public int read_standard(byte[] buf) {
byte[] content = ReadData();
// Log.i("pupu原始数据", printByte(content));
Log.i("13", ASCII2HexString(content, 22));
if (content[0] == 'W') {// 称重数据
byte status = content[4];
byte[] net_weight = new byte[7];
byte sep = 'P';
byte[] tare_weight = new byte[7];
System.arraycopy(content, 5, net_weight, 0, 6);
System.arraycopy(content, 12, tare_weight, 0, 6);
buf[0] = status;
for (int i = 0; i < 6; i++) {
buf[i + 1] = net_weight[i];
}
buf[7] = sep;
for (int j = 0; j < 6; j++) {
buf[j + 8] = tare_weight[j];
}
return 0;
} else if (content[0] == 'R') {// 指令结果
System.arraycopy(content, 0, buf, 0, 12);
return 1;
} else if (content[0] == 'E') {// 错误
System.arraycopy(content, 0, buf, 0, 12);
return 2;
}
return 2;
}
/**
* 供外部判断是否已经成功连接
*
* @return
*/
public boolean isConnected() {
return !new String(ReadData()).startsWith("E");
}
/**
* 重置零点
*
* @return true:指令发送成功;false:指令发送失败
* @author pupu
*/
public boolean resetZero() {
return OutPutSerialPort("ZERO\r\n");
}
/**
* 设置皮重
*
* @param tare 皮重,单位kg
* @return
* @author pupu
*/
public boolean setTare(double tare) {
DecimalFormat df = new DecimalFormat("######0.000");
return OutPutSerialPort("YTARE " + df.format(tare) + "\r\n");
}
/**
* 重量标定
*
* @param weight 标准重量
* @return
* @author pupu
*/
public boolean markWeight(double weight) {
DecimalFormat df = new DecimalFormat("######0.000");
return OutPutSerialPort("CALL " + df.format(weight) + "\r\n");
}
/**
* 设置重力系数
*
* @param gravity 重力系数
* @return
* @author pupu
*/
public boolean setGravity(double gravity) {
return OutPutSerialPort("GSET " + gravity + "\r\n");
}
// 置零
public void send_zero() {
OutPutSerialPort("ZERO\r\n");
}
// 零位标定
public void calibration_zero() {
OutPutSerialPort("CALZ\r\n");
}
// 量程标定
public void calibration_range(double weight) {
DecimalFormat df = new DecimalFormat("######0.000");
OutPutSerialPort("CALL " + df.format(weight) + "\r\n");
}
// 设置重力
public void calibration_gravity(double d) {
OutPutSerialPort("GSET " + d + "\r\n");
}
// 去皮
public void send_tare() {
OutPutSerialPort("TARE\r\n");
}
// 设置皮重
public void send_ytare(double d) {
DecimalFormat df = new DecimalFormat("######0.000");
OutPutSerialPort("YTARE " + df.format(d) + "\r\n");
}
// 设置其他参数
public void send_other(int x1, int x2, int x3, int x4) {
OutPutSerialPort("PSET" + x1 + x2 + x3 + x4 + "\r\n");
}
// 参数设定
public void send_parameter(int model, int full, int mid, int deci, int div, int div2) {
OutPutSerialPort("SETALL " + model + " " + full + " " + mid + " " + deci + " " + div + " " + div2 + " \r\n");
}
// 获取标定状态
public void calibration() {
OutPutSerialPort("KSGET\r\n");
}
// 获取AD版本号
public void get_version() {
OutPutSerialPort("version\r\n");
}
public void SCL_close() {
comio.readFinish();
}
}
...@@ -4,8 +4,8 @@ import android.content.Context; ...@@ -4,8 +4,8 @@ import android.content.Context;
import android.os.CountDownTimer; import android.os.CountDownTimer;
import android.util.Log; import android.util.Log;
import com.pupu.chuangjieweighing.ReadSerialPort; import pupu.chuangjieweighing.ReadSerialPort;
import com.pupu.chuangjieweighing.SerialPortFunction; import pupu.chuangjieweighing.SerialPortFunction;
/** /**
......
...@@ -6,11 +6,11 @@ import android.content.Intent; ...@@ -6,11 +6,11 @@ import android.content.Intent;
import android.content.ServiceConnection; import android.content.ServiceConnection;
import android.os.IBinder; import android.os.IBinder;
import android.os.RemoteException; import android.os.RemoteException;
import android.util.Log;
import com.hisense.optionalservice.aidl.OnDataReceiveListener; import com.hisense.optionalservice.aidl.OnDataReceiveListener;
import com.hisense.optionalservice.aidl.OptionalApi; import com.hisense.optionalservice.aidl.OptionalApi;
import com.hisense.optionalservice.aidl.UartScale; import com.hisense.optionalservice.aidl.UartScale;
import com.miya.utils.D;
/** /**
* 海信称重实现子类 * 海信称重实现子类
...@@ -125,7 +125,7 @@ public class HisenseWeighing extends BaseWeighing { ...@@ -125,7 +125,7 @@ public class HisenseWeighing extends BaseWeighing {
uartScale.setOnDataReceiveListener(new OnDataReceiveListener.Stub() { uartScale.setOnDataReceiveListener(new OnDataReceiveListener.Stub() {
@Override @Override
public void onDataReceive(float weight, int status) throws RemoteException { public void onDataReceive(float weight, int status) throws RemoteException {
Log.i("pupu", "weight==>" + weight + ";" + "status==>" + status); D.i("pupu", "weight==>" + weight + ";" + "status==>" + status);
if (status > 0) { if (status > 0) {
//读取正常 //读取正常
curWeight = parseKg2g(weight + ""); curWeight = parseKg2g(weight + "");
...@@ -142,23 +142,23 @@ public class HisenseWeighing extends BaseWeighing { ...@@ -142,23 +142,23 @@ public class HisenseWeighing extends BaseWeighing {
} }
} }
}); });
Log.i(TAG, "称重连接成功!"); D.i(TAG, "称重连接成功!");
} catch (Exception ex) { } catch (Exception ex) {
//设置监听失败 //设置监听失败
ex.printStackTrace(); ex.printStackTrace();
} }
} else { } else {
//连接失败 //连接失败
Log.i(TAG, "防损称连接失败"); D.i(TAG, "防损称连接失败");
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
//连接失败 //连接失败
Log.i(TAG, "防损称连接失败"); D.i(TAG, "防损称连接失败");
} }
} else { } else {
//连接服务失败 //连接服务失败
Log.i(TAG, "防损称连接失败"); D.i(TAG, "防损称连接失败");
} }
} }
......
package com.miya.weighing; package com.miya.weighing;
import android.content.Context; import android.content.Context;
import com.miya.utils.CpuUtils;
import com.miya.utils.D;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
import cn.wintec.wtandroidjar.SCL; import cn.wintec.wtandroidjar.SCL;
/** /**
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment