Commit 8f22acbe authored by pengguangpu's avatar pengguangpu

扩散jar包代码,完善weighing moudle

parent 5c645801
......@@ -4,6 +4,20 @@
android:layout_height="match_parent"
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
android:id="@+id/btnWeighing"
android:layout_width="match_parent"
......
......@@ -4,6 +4,20 @@
android:layout_height="match_parent"
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
android:id="@+id/tvResult"
android:layout_width="wrap_content"
......
<resources>
<string name="app_name">hardware</string>
<string name="app_name">米雅硬件开放平台</string>
</resources>
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</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 {
//商米称重驱动
implementation files('libs/scale-service-part-lib-1.1.jar')
//创捷称重驱动jar包(自制)
implementation files('libs/chuangjieweighing.jar')
// implementation files('libs/chuangjieweighing.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()]);
}
}
This diff is collapsed.
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;
import android.os.CountDownTimer;
import android.util.Log;
import com.pupu.chuangjieweighing.ReadSerialPort;
import com.pupu.chuangjieweighing.SerialPortFunction;
import pupu.chuangjieweighing.ReadSerialPort;
import pupu.chuangjieweighing.SerialPortFunction;
/**
......
......@@ -6,11 +6,11 @@ import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import com.hisense.optionalservice.aidl.OnDataReceiveListener;
import com.hisense.optionalservice.aidl.OptionalApi;
import com.hisense.optionalservice.aidl.UartScale;
import com.miya.utils.D;
/**
* 海信称重实现子类
......@@ -125,7 +125,7 @@ public class HisenseWeighing extends BaseWeighing {
uartScale.setOnDataReceiveListener(new OnDataReceiveListener.Stub() {
@Override
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) {
//读取正常
curWeight = parseKg2g(weight + "");
......@@ -142,23 +142,23 @@ public class HisenseWeighing extends BaseWeighing {
}
}
});
Log.i(TAG, "称重连接成功!");
D.i(TAG, "称重连接成功!");
} catch (Exception ex) {
//设置监听失败
ex.printStackTrace();
}
} else {
//连接失败
Log.i(TAG, "防损称连接失败");
D.i(TAG, "防损称连接失败");
}
} catch (Exception e) {
e.printStackTrace();
//连接失败
Log.i(TAG, "防损称连接失败");
D.i(TAG, "防损称连接失败");
}
} else {
//连接服务失败
Log.i(TAG, "防损称连接失败");
D.i(TAG, "防损称连接失败");
}
}
......
package com.miya.weighing;
import android.content.Context;
import com.miya.utils.CpuUtils;
import com.miya.utils.D;
import java.util.Timer;
import java.util.TimerTask;
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