Initial commit

This commit is contained in:
2025-05-13 19:24:51 +02:00
commit a950f49678
10604 changed files with 932663 additions and 0 deletions

View File

@@ -0,0 +1,71 @@
package com.ubtrobot.analytics;
import android.os.SystemClock;
/* loaded from: classes2.dex */
public class ActivenessRecord {
private String a;
private String b;
private String c;
private long e = System.currentTimeMillis();
private long f = SystemClock.elapsedRealtime();
private long d = this.e - this.f;
public ActivenessRecord(String str) {
this.a = str;
}
public ActivenessRecord a(String str) {
this.b = str;
return this;
}
public ActivenessRecord b(String str) {
this.c = str;
return this;
}
public ActivenessRecord c(long j) {
this.e = j;
return this;
}
public long d() {
return this.e;
}
public String e() {
String str = this.b;
return str != null ? str : "";
}
public String f() {
return this.c;
}
public String toString() {
return "ActivenessRecord{eventId='" + this.a + "', userId='" + this.b + "', version='" + this.c + "', startedAt=" + this.d + ", ticktockAt=" + this.e + ", duration=" + this.f + '}';
}
public ActivenessRecord a(long j) {
this.f = j;
return this;
}
public ActivenessRecord b(long j) {
this.d = j;
return this;
}
public long c() {
return this.d;
}
public long a() {
return this.f;
}
public String b() {
return this.a;
}
}

View File

@@ -0,0 +1,74 @@
package com.ubtrobot.analytics;
import android.content.ContentValues;
import android.database.Cursor;
import android.util.Log;
import com.ubt.jimu.controller.data.widget.JockstickDataConverter;
import com.unity3d.ads.metadata.MediationMetaData;
/* loaded from: classes2.dex */
public class ActivenessScheme {
public static void a(AnalyticsDBHelper analyticsDBHelper) {
Log.i("Analytics", "Create table: activeness");
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("CREATE TABLE IF NOT EXISTS ");
stringBuffer.append("activeness");
stringBuffer.append("(");
stringBuffer.append(JockstickDataConverter.ID);
stringBuffer.append(" INTEGER PRIMARY KEY AUTOINCREMENT,");
stringBuffer.append("event_id");
stringBuffer.append(" VARCHAR NOT NULL,");
stringBuffer.append("user_id");
stringBuffer.append(" VARCHAR DEFAULT '',");
stringBuffer.append(MediationMetaData.KEY_VERSION);
stringBuffer.append(" VARCHAR DEFAULT '',");
stringBuffer.append("started_at");
stringBuffer.append(" INTEGER DEFAULT 0,");
stringBuffer.append("ticktock_at");
stringBuffer.append(" INTEGER DEFAULT 0,");
stringBuffer.append("duration");
stringBuffer.append(" INTEGER DEFAULT 0");
stringBuffer.append(")");
analyticsDBHelper.a(stringBuffer.toString());
}
public static void b(AnalyticsDBHelper analyticsDBHelper) {
Log.i("Analytics", "Running upgradeToVersion4 ...");
if (analyticsDBHelper.a("activeness", "user_id")) {
return;
}
String format = String.format("ALTER TABLE %s ADD COLUMN %s VARCHAR DEFAULT ''", "activeness", "user_id");
String format2 = String.format("ALTER TABLE %s ADD COLUMN %s VARCHAR DEFAULT ''", "activeness", MediationMetaData.KEY_VERSION);
analyticsDBHelper.b(format);
analyticsDBHelper.b(format2);
}
public static class Converters {
static ContentValues a(ActivenessRecord activenessRecord) {
ContentValues contentValues = new ContentValues();
contentValues.put("event_id", activenessRecord.b());
contentValues.put("user_id", activenessRecord.e());
contentValues.put(MediationMetaData.KEY_VERSION, activenessRecord.f());
contentValues.put("started_at", Long.valueOf(activenessRecord.c()));
contentValues.put("ticktock_at", Long.valueOf(activenessRecord.d()));
contentValues.put("duration", Long.valueOf(activenessRecord.a()));
return contentValues;
}
static ActivenessRecord a(Cursor cursor) {
String string = cursor.getString(cursor.getColumnIndex("event_id"));
String string2 = cursor.getString(cursor.getColumnIndex("user_id"));
String string3 = cursor.getString(cursor.getColumnIndex(MediationMetaData.KEY_VERSION));
long j = cursor.getLong(cursor.getColumnIndex("started_at"));
long j2 = cursor.getLong(cursor.getColumnIndex("ticktock_at"));
long j3 = cursor.getLong(cursor.getColumnIndex("duration"));
ActivenessRecord activenessRecord = new ActivenessRecord(string);
activenessRecord.a(string2);
activenessRecord.b(string3);
activenessRecord.b(j);
activenessRecord.c(j2);
activenessRecord.a(j3);
return activenessRecord;
}
}
}

View File

@@ -0,0 +1,91 @@
package com.ubtrobot.analytics;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import com.ubt.jimu.controller.data.widget.JockstickDataConverter;
import com.ubtrobot.analytics.ActivenessScheme;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
/* loaded from: classes2.dex */
public class ActivenessStorage {
private AnalyticsDBHelper a;
public ActivenessStorage(Context context) {
this.a = AnalyticsDBHelper.a(context);
}
public void a() throws IOException {
synchronized (this) {
String format = String.format("DELETE FROM %s WHERE %s IN(SELECT %s FROM(SELECT %s FROM %s GROUP BY %s HAVING count(%s) > 1))AND %s NOT IN(SELECT %s FROM(SELECT max(%s), %s FROM %s GROUP BY %s HAVING count(%s) > 1))", "activeness", "started_at", "started_at", "started_at", "activeness", "started_at", "started_at", "duration", "duration", "duration", "duration", "activeness", "started_at", "started_at");
Log.i("Analytics", "SQL deleteRepetition: " + format);
this.a.b(format);
}
}
public void b(ActivenessRecord activenessRecord) throws IOException {
synchronized (this) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("event_id");
stringBuffer.append(" = ? AND ");
stringBuffer.append("user_id");
stringBuffer.append(" = ? AND ");
stringBuffer.append(JockstickDataConverter.ID);
stringBuffer.append(" IN (SELECT ");
stringBuffer.append(JockstickDataConverter.ID);
stringBuffer.append(" FROM ");
stringBuffer.append("activeness");
stringBuffer.append(" ORDER BY ");
stringBuffer.append("ticktock_at");
stringBuffer.append(" DESC");
stringBuffer.append(" LIMIT 1");
stringBuffer.append(")");
this.a.a("activeness", ActivenessScheme.Converters.a(activenessRecord), stringBuffer.toString(), new String[]{activenessRecord.b(), activenessRecord.e()});
}
}
public int a(String str, int i) throws IOException {
int a;
synchronized (this) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("event_id");
stringBuffer.append(" = ? AND ");
stringBuffer.append(JockstickDataConverter.ID);
stringBuffer.append(" IN (SELECT ");
stringBuffer.append(JockstickDataConverter.ID);
stringBuffer.append(" FROM ");
stringBuffer.append("activeness");
stringBuffer.append(" ORDER BY ");
stringBuffer.append("ticktock_at");
stringBuffer.append(" ASC");
stringBuffer.append(" LIMIT ");
stringBuffer.append(i);
stringBuffer.append(")");
a = this.a.a("activeness", stringBuffer.toString(), new String[]{str});
}
return a;
}
public void a(ActivenessRecord activenessRecord) throws IOException {
synchronized (this) {
this.a.a("activeness", ActivenessScheme.Converters.a(activenessRecord));
}
}
public List<ActivenessRecord> a(String str) throws IOException {
synchronized (this) {
Cursor d = this.a.d(String.format("SELECT * FROM %s WHERE %s = '%s'", "activeness", "event_id", str));
LinkedList linkedList = new LinkedList();
if (d == null) {
return linkedList;
}
while (d.moveToNext()) {
linkedList.add(ActivenessScheme.Converters.a(d));
}
d.close();
return linkedList;
}
}
}

View File

@@ -0,0 +1,5 @@
package com.ubtrobot.analytics;
/* loaded from: classes2.dex */
public interface Analytics {
}

View File

@@ -0,0 +1,186 @@
package com.ubtrobot.analytics;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDiskIOException;
import android.database.sqlite.SQLiteFullException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.Iterator;
import java.util.List;
/* loaded from: classes2.dex */
public class AnalyticsDBHelper extends SQLiteOpenHelper {
private static final byte[] a = new byte[0];
private static volatile AnalyticsDBHelper b;
private static volatile SQLiteDatabase c;
private AnalyticsDBHelper(Context context) {
super(context, "analytics", (SQLiteDatabase.CursorFactory) null, 4);
}
public static AnalyticsDBHelper a(Context context) {
if (b != null) {
return b;
}
synchronized (a) {
if (b != null) {
return b;
}
b = new AnalyticsDBHelper(context);
return b;
}
}
public void b(String str) {
try {
a().execSQL(str);
} catch (SQLiteDiskIOException e) {
Log.e("Analytics", "Exec sql fail, msg:" + e.getMessage());
}
}
public int c(String str) {
try {
Cursor rawQuery = a().rawQuery("SELECT COUNT(*) FROM " + str, null);
try {
rawQuery.moveToFirst();
return (int) rawQuery.getLong(0);
} finally {
rawQuery.close();
}
} catch (SQLiteDiskIOException e) {
Log.e("Analytics", "GetCount fail, msg:" + e.getMessage());
return 0;
}
}
public Cursor d(String str) {
try {
return a().rawQuery(str, null);
} catch (SQLiteDiskIOException e) {
Log.e("Analytics", "CheckColumnExists fail, msg:" + e.getMessage());
return null;
}
}
@Override // android.database.sqlite.SQLiteOpenHelper
public void onCreate(SQLiteDatabase sQLiteDatabase) {
c = sQLiteDatabase;
EventScheme.a(b);
ActivenessScheme.a(b);
}
@Override // android.database.sqlite.SQLiteOpenHelper
public void onUpgrade(SQLiteDatabase sQLiteDatabase, int i, int i2) {
c = sQLiteDatabase;
while (i <= i2) {
if (i == 2) {
b();
} else if (i == 3) {
c();
} else if (i == 4) {
d();
}
i++;
}
}
private void b() {
EventScheme.b(b);
}
private void d() {
EventScheme.d(b);
ActivenessScheme.b(b);
}
private void c() {
EventScheme.c(b);
ActivenessScheme.a(b);
}
public void a(String str) {
Log.i("Analytics", "Create table: " + str);
try {
a().execSQL(str);
} catch (SQLiteDiskIOException e) {
Log.e("Analytics", "Create table fail, msg:" + e.getMessage());
}
}
private SQLiteDatabase a() {
c = c != null ? c : b.getWritableDatabase();
return c;
}
public void a(List<String> list) {
try {
a().beginTransaction();
Iterator<String> it = list.iterator();
while (it.hasNext()) {
a().execSQL(it.next());
}
a().setTransactionSuccessful();
a().endTransaction();
} catch (SQLiteDiskIOException e) {
Log.e("Analytics", "Exec sql list fail, msg:" + e.getMessage());
}
}
public int a(String str, String str2, String[] strArr) {
try {
return a().delete(str, str2, strArr);
} catch (SQLiteDiskIOException e) {
Log.e("Analytics", "Delete fail, msg:" + e.getMessage());
return 0;
} catch (SQLiteFullException e2) {
Log.e("Analytics", "Delete fail, msg:" + e2.getMessage());
a().execSQL(String.format("DROP TABLE %s", str));
if (str.equals("event")) {
EventScheme.a(b);
} else if (str.equals("activeness")) {
ActivenessScheme.a(b);
}
return 0;
}
}
public void a(String str, ContentValues contentValues, String str2, String[] strArr) {
try {
SQLiteDatabase a2 = a();
a2.beginTransaction();
if (a2.update(str, contentValues, str2, strArr) <= 0) {
a2.insert(str, null, contentValues);
}
a2.setTransactionSuccessful();
a2.endTransaction();
} catch (SQLiteDiskIOException e) {
Log.e("Analytics", "UpdateIfExist fail, msg:" + e.getMessage());
}
}
public void a(String str, ContentValues contentValues) {
try {
a().insert(str, null, contentValues);
} catch (SQLiteDiskIOException e) {
Log.e("Analytics", "Insert fail, msg:" + e.getMessage());
}
}
public boolean a(String str, String str2) {
try {
Cursor rawQuery = a().rawQuery("select * from sqlite_master where name = ? and sql like ?", new String[]{str, "%" + str2 + "%"});
boolean moveToFirst = rawQuery.moveToFirst();
if (!rawQuery.isClosed()) {
rawQuery.close();
}
return moveToFirst;
} catch (SQLiteDiskIOException e) {
Log.e("Analytics", "CheckColumnExists fail, msg:" + e.getMessage());
return false;
}
}
}

View File

@@ -0,0 +1,550 @@
package com.ubtrobot.analytics;
import android.content.Context;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.util.Log;
import com.ubt.jimu.base.entities.Course;
import com.ubt.jimu.base.mvp.SingleClickListener;
import com.ubtrobot.analytics.NetWorkChangeReceiver;
import com.ubtrobot.analytics.Retry;
import com.ubtrobot.analytics.device.DeviceInfo;
import com.ubtrobot.analytics.event.ActivenessEventSource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
/* loaded from: classes2.dex */
public class AnalyticsServiceImpl implements Analytics {
private static final long q = TimeUnit.MINUTES.toMillis(5);
private volatile long d;
private DeviceInfo f;
private boolean g;
private Executor h;
private MemEventStorage i;
private EventStorage j;
private RealtimeReport k;
private HttpReport l;
private ActivenessEventSource n;
private Handler o;
private NetWorkChangeReceiver p;
private final byte[] a = new byte[0];
private final byte[] b = new byte[0];
private volatile long c = b() + 20;
private long e = q;
private boolean m = true;
private class RealtimeReport {
private volatile Set<String> a;
private Context b;
private MemEventStorage c;
private boolean d;
private boolean e;
private Retry f;
private Runnable g;
/* JADX INFO: Access modifiers changed from: private */
public boolean g() {
synchronized (AnalyticsServiceImpl.this.b) {
int a = this.c.a();
List<Event> a2 = this.c.a(a);
boolean b = AnalyticsServiceImpl.this.b(a2);
Log.i("Analytics", "Forthwith report event report result:" + b);
if (!b) {
this.d = true;
return false;
}
if (!this.d) {
this.c.b(a);
return true;
}
this.d = false;
try {
this.c.b(a);
AnalyticsServiceImpl.this.j.a(a2);
return true;
} catch (IOException unused) {
Log.w("Analytics", "Remove mDiskStorage is fail.");
this.d = true;
return false;
}
}
}
private RealtimeReport(Context context) {
this.b = context;
this.c = new MemEventStorage(new MemoryEventStorage());
this.a = new HashSet();
f();
this.g = new Runnable(AnalyticsServiceImpl.this) { // from class: com.ubtrobot.analytics.AnalyticsServiceImpl.RealtimeReport.1
@Override // java.lang.Runnable
public void run() {
if (RealtimeReport.this.g()) {
RealtimeReport.this.f.b();
}
}
};
this.f = new Retry(new Retry.RetryListener(AnalyticsServiceImpl.this) { // from class: com.ubtrobot.analytics.AnalyticsServiceImpl.RealtimeReport.2
@Override // com.ubtrobot.analytics.Retry.RetryListener
public void a() {
Log.i("Analytics", "Report retrying ...");
AnalyticsServiceImpl.this.h.execute(RealtimeReport.this.g);
}
});
}
/* JADX INFO: Access modifiers changed from: private */
public boolean b(boolean z) {
synchronized (AnalyticsServiceImpl.this.b) {
try {
if (!z) {
try {
if (!a()) {
Log.i("Analytics", "Realtime event sp is updated.");
return false;
}
} catch (ReportException e) {
Log.w("Analytics", "Request realtime is fail.", e);
this.e = false;
return false;
}
}
RealtimeEvent a = AnalyticsServiceImpl.this.l.a(b());
if (a == null) {
this.e = false;
return false;
}
Log.i("Analytics", "Realtime: " + a.toString());
this.a.addAll(a.b());
a(a.a(), this.a);
this.e = true;
return true;
} catch (Throwable th) {
throw th;
}
}
}
/* JADX INFO: Access modifiers changed from: private */
public void c() {
this.a.addAll(this.b.getSharedPreferences("realtime_event_id", 0).getStringSet("event_id_set", new HashSet()));
}
private long d() {
return this.b.getSharedPreferences("realtime_event_id", 0).getLong("next_update_time", 0L);
}
/* JADX INFO: Access modifiers changed from: private */
public void e() {
Log.i("Analytics", "Force refresh realtime eventId list.");
a(true);
}
private void f() {
Log.i("Analytics", "Refresh realtime eventId list.");
a(false);
}
private void a(final boolean z) {
AnalyticsServiceImpl.this.h.execute(new Runnable() { // from class: com.ubtrobot.analytics.AnalyticsServiceImpl.RealtimeReport.3
@Override // java.lang.Runnable
public void run() {
if (RealtimeReport.this.b(z)) {
Log.i("Analytics", "Read realtime event from sp.");
RealtimeReport.this.c();
}
}
});
}
private boolean a() {
if (!this.e) {
return true;
}
if (d() > System.currentTimeMillis()) {
Log.i("Analytics", "Update realtime sp time:" + d());
return false;
}
this.e = false;
return true;
}
private void a(String str, Set<String> set) {
SharedPreferences sharedPreferences = this.b.getSharedPreferences("realtime_event_id", 0);
long currentTimeMillis = System.currentTimeMillis() + 3600000;
if (str.equals(b())) {
Log.i("Analytics", "Update realtime sp: next_update_time.");
sharedPreferences.edit().putLong("next_update_time", currentTimeMillis).apply();
} else {
Log.i("Analytics", "Update realtime sp.");
sharedPreferences.edit().putString(Course.TYPE_BLOCKLY, str).putStringSet("event_id_set", set).putLong("next_update_time", currentTimeMillis).apply();
}
}
private String b() {
return this.b.getSharedPreferences("realtime_event_id", 0).getString(Course.TYPE_BLOCKLY, "");
}
/* JADX INFO: Access modifiers changed from: private */
public boolean a(String str) {
if (AnalyticsServiceImpl.this.k.a()) {
f();
}
return this.a.contains(str);
}
/* JADX INFO: Access modifiers changed from: private */
public void a(final Event event) {
AnalyticsServiceImpl.this.h.execute(new Runnable() { // from class: com.ubtrobot.analytics.AnalyticsServiceImpl.RealtimeReport.4
@Override // java.lang.Runnable
public void run() {
RealtimeReport.this.c.a(event);
if (RealtimeReport.this.g()) {
return;
}
AnalyticsServiceImpl.this.c((List<Event>) Collections.singletonList(event));
RealtimeReport.this.f.a();
}
});
}
}
private class TimerReportRunnable implements Runnable {
private long a = a();
public TimerReportRunnable() {
}
private long a() {
Calendar calendar = Calendar.getInstance();
calendar.set(calendar.get(1), calendar.get(2), calendar.get(5), 23, 59, 59);
return calendar.getTimeInMillis();
}
private void b() {
if (System.currentTimeMillis() > this.a) {
AnalyticsServiceImpl.this.g();
c();
this.a = a();
}
}
private void c() {
AnalyticsServiceImpl.this.h.execute(new Runnable() { // from class: com.ubtrobot.analytics.AnalyticsServiceImpl.TimerReportRunnable.1
@Override // java.lang.Runnable
public void run() {
AnalyticsServiceImpl.this.f();
}
});
}
@Override // java.lang.Runnable
public void run() {
b();
AnalyticsServiceImpl.this.o.postDelayed(this, 15000L);
}
}
public AnalyticsServiceImpl(Context context, String str, String str2, String str3, ActivenessEventSource activenessEventSource, Executor executor) {
this.h = executor;
Strategy strategy = Strategy.DEFAULT;
this.i = new MemEventStorage(new MemoryEventStorage());
this.l = new HttpReport(context, str, str2, str3);
this.j = new DiskEventStorage(context);
this.k = new RealtimeReport(context);
this.n = activenessEventSource;
a(this.n);
this.o = new Handler(Looper.getMainLooper());
this.o.post(new TimerReportRunnable());
a(context);
c();
}
private static class MemEventStorage implements EventStorage {
private final EventStorage a;
MemEventStorage(EventStorage eventStorage) {
this.a = eventStorage;
}
@Override // com.ubtrobot.analytics.EventStorage
public void a(Event event) {
try {
this.a.a(event);
} catch (IOException e) {
throw new IllegalStateException("Impossible(writeEvent) IOException on MemoryStorage", e);
}
}
@Override // com.ubtrobot.analytics.EventStorage
public void b(List<Event> list) {
try {
this.a.b(list);
} catch (IOException e) {
throw new IllegalStateException("Impossible(writeEvents) IOException on MemoryStorage", e);
}
}
@Override // com.ubtrobot.analytics.EventStorage
public int a() {
try {
return this.a.a();
} catch (IOException e) {
throw new IllegalStateException("Impossible(getEventCount) IOException on MemoryStorage", e);
}
}
@Override // com.ubtrobot.analytics.EventStorage
public void b(int i) {
try {
this.a.b(i);
} catch (IOException e) {
throw new IllegalStateException("Impossible IOException on MemoryStorage", e);
}
}
@Override // com.ubtrobot.analytics.EventStorage
public List<Event> a(int i) {
try {
return this.a.a(i);
} catch (IOException e) {
throw new IllegalStateException("Impossible IOException on MemoryStorage", e);
}
}
@Override // com.ubtrobot.analytics.EventStorage
public void a(List<Event> list) throws IOException {
throw new IllegalStateException("MemEventStorage nonsupport removeEvents(List<Event>).");
}
}
private void c() {
this.h.execute(new Runnable() { // from class: com.ubtrobot.analytics.AnalyticsServiceImpl.1
@Override // java.lang.Runnable
public void run() {
Log.i("Analytics", "First report.");
AnalyticsServiceImpl.this.f();
}
});
}
private List<Event> d() {
ArrayList arrayList = new ArrayList();
try {
return this.j.a(50);
} catch (IOException unused) {
Log.w("Analytics", "Operate event disk storage failed.");
return arrayList;
}
}
private void e() {
try {
if (this.f == null) {
Log.w("Analytics", "Please AnalyticsServiceImpl.setDeviceInfo.");
} else {
this.l.a(this.f);
this.g = true;
}
} catch (ReportException unused) {
this.g = false;
}
}
/* JADX INFO: Access modifiers changed from: private */
public void f() {
synchronized (this.b) {
while (true) {
if (!a()) {
break;
}
List<Event> d = d();
if (!b(d)) {
Log.i("Analytics", "Report fail, count: " + d.size());
break;
}
Log.i("Analytics", "Report success, count: " + d.size());
a(d);
}
if (!this.g) {
e();
}
this.d = b() + this.e;
}
}
/* JADX INFO: Access modifiers changed from: private */
public void g() {
synchronized (this.a) {
while (this.i.a() > 0) {
List<Event> a = this.i.a(SingleClickListener.FAST_CLICK_DELAY_TIME);
if (a.isEmpty()) {
return;
}
if (c(a)) {
this.i.b(a.size());
}
}
this.c = b() + 20;
}
}
/* JADX INFO: Access modifiers changed from: private */
public boolean h() {
return b() - this.d > 0;
}
private boolean i() {
return this.i.a() >= 500 || b() - this.c >= 0;
}
private void a(Context context) {
this.p = new NetWorkChangeReceiver(new NetWorkChangeReceiver.INetWorkChange() { // from class: com.ubtrobot.analytics.AnalyticsServiceImpl.2
@Override // com.ubtrobot.analytics.NetWorkChangeReceiver.INetWorkChange
public void a() {
AnalyticsServiceImpl.this.k.e();
}
});
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
intentFilter.addAction("android.net.wifi.STATE_CHANGE");
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
context.registerReceiver(this.p, intentFilter);
}
public void b(boolean z) {
this.l.a(z);
}
private void b(Event event) {
this.i.a(event);
if (i() || h()) {
this.h.execute(new Runnable() { // from class: com.ubtrobot.analytics.AnalyticsServiceImpl.4
@Override // java.lang.Runnable
public void run() {
AnalyticsServiceImpl.this.g();
if (AnalyticsServiceImpl.this.h()) {
Log.i("Analytics", "Report start...");
AnalyticsServiceImpl.this.f();
}
}
});
}
}
/* JADX INFO: Access modifiers changed from: private */
public boolean c(List<Event> list) {
try {
this.j.b(list);
return true;
} catch (IOException unused) {
Log.w("Analytics", "Save events to disk failed.");
return false;
}
}
private long b() {
return SystemClock.elapsedRealtime();
}
private void a(final ActivenessEventSource activenessEventSource) {
this.h.execute(new Runnable() { // from class: com.ubtrobot.analytics.AnalyticsServiceImpl.3
@Override // java.lang.Runnable
public void run() {
try {
List<Event> a = activenessEventSource.a();
int size = a.size();
if (size <= 0) {
Log.i("Analytics", "ActivenessEvent is not exist.");
return;
}
Log.i("Analytics", "ActivenessEvent count:" + size);
boolean z = false;
int i = 0;
int i2 = 0;
while (true) {
if (i >= size) {
break;
}
i += 50;
if (i > size) {
i = size;
}
if (!AnalyticsServiceImpl.this.c(a.subList(i2, i))) {
z = true;
break;
}
i2 = i;
}
if (z) {
Log.i("Analytics", "ActivenessEvent record to event table fail.");
} else {
Log.i("Analytics", "ActivenessEvent record to event table success.");
activenessEventSource.a(size);
}
} catch (IOException unused) {
}
}
});
}
/* JADX INFO: Access modifiers changed from: private */
public boolean b(List<Event> list) {
try {
this.l.a(list);
return true;
} catch (ReportException e) {
Log.e("Analytics", "Report Error:" + e.getMessage());
if (e.causedByInternalServerError()) {
Log.w("Analytics", "Report(reportEvents) events failed due to server error.");
}
return false;
}
}
public void a(boolean z) {
this.m = z;
}
public void a(Event event) {
if (this.m) {
if (this.k.a(event.getEventId())) {
Log.i("Analytics", "Event is forthwith report event.");
this.k.a(event);
} else {
Log.i("Analytics", "Event is not forthwith report event.");
b(event);
}
}
}
private boolean a() {
try {
return this.j.a() > 0;
} catch (IOException unused) {
Log.w("Analytics", "Report(getEventCount) events failed due to server error.");
return false;
}
}
private void a(List<Event> list) {
try {
this.j.b(list.size());
} catch (IOException unused) {
Log.w("Analytics", "Report(removeEvents) events failed due to server error.");
}
}
public void a(DeviceInfo deviceInfo) {
this.f = deviceInfo;
}
}

View File

@@ -0,0 +1,120 @@
package com.ubtrobot.analytics;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import com.ubt.jimu.controller.data.widget.JockstickDataConverter;
import com.ubtrobot.analytics.EventScheme;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/* loaded from: classes2.dex */
public class DiskEventStorage implements EventStorage {
private int a = -1;
private AnalyticsDBHelper b;
public DiskEventStorage(Context context) {
this.b = AnalyticsDBHelper.a(context);
}
@Override // com.ubtrobot.analytics.EventStorage
public void a(Event event) throws IOException {
synchronized (this) {
b(Collections.singletonList(event));
}
}
@Override // com.ubtrobot.analytics.EventStorage
public void b(List<Event> list) throws IOException {
synchronized (this) {
this.b.b(EventScheme.Converters.a(list));
this.a = -1;
}
}
@Override // com.ubtrobot.analytics.EventStorage
public int a() throws IOException {
int i;
synchronized (this) {
this.a = this.a > 0 ? this.a : this.b.c("event");
i = this.a;
}
return i;
}
@Override // com.ubtrobot.analytics.EventStorage
public void b(int i) throws IOException {
synchronized (this) {
this.b.a("event", String.format("%s IN (SELECT %s FROM %s LIMIT %s)", JockstickDataConverter.ID, JockstickDataConverter.ID, "event", Integer.valueOf(i)), null);
this.a = -1;
}
}
@Override // com.ubtrobot.analytics.EventStorage
public List<Event> a(int i) throws IOException {
synchronized (this) {
LinkedList linkedList = new LinkedList();
int i2 = i / 5;
int i3 = 0;
while (true) {
if (i3 > i) {
break;
}
i3 += i2;
Cursor d = this.b.d(String.format("SELECT * FROM %s ORDER BY %s ASC LIMIT %s, %s", "event", JockstickDataConverter.ID, Integer.valueOf(i3), Integer.valueOf(i3)));
if (d == null) {
return Collections.emptyList();
}
try {
if (d.getCount() == 0) {
break;
}
while (d.moveToNext()) {
linkedList.add(EventScheme.Converters.a(d));
}
d.close();
} finally {
d.close();
}
}
return linkedList;
}
}
@Override // com.ubtrobot.analytics.EventStorage
public void a(List<Event> list) throws IOException {
synchronized (this) {
LinkedList linkedList = new LinkedList();
for (Event event : list) {
StringBuilder sb = new StringBuilder();
sb.append("DELETE FROM ");
sb.append("event");
sb.append(" WHERE ");
sb.append(JockstickDataConverter.ID);
sb.append(" IN(SELECT ");
sb.append(JockstickDataConverter.ID);
sb.append(" FROM ");
sb.append("event");
sb.append(" WHERE ");
sb.append("event_id");
sb.append(" = '");
sb.append(event.getEventId());
sb.append("' AND ");
sb.append("category");
sb.append(" = '");
sb.append(event.getCategory());
sb.append("' AND ");
sb.append("recorded_at");
sb.append(" = '");
sb.append(event.getRecordedAt());
sb.append("'");
sb.append(")");
linkedList.add(sb.toString());
Log.i("Analytics", "Remove event sql: " + sb.toString());
}
this.b.a(linkedList);
}
}
}

View File

@@ -0,0 +1,183 @@
package com.ubtrobot.analytics;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.HashMap;
import java.util.Map;
/* loaded from: classes2.dex */
public class Event implements Parcelable {
public static final Parcelable.Creator<Event> CREATOR = new Parcelable.Creator<Event>() { // from class: com.ubtrobot.analytics.Event.1
/* JADX WARN: Can't rename method to resolve collision */
@Override // android.os.Parcelable.Creator
public Event createFromParcel(Parcel parcel) {
return new Event(parcel);
}
/* JADX WARN: Can't rename method to resolve collision */
@Override // android.os.Parcelable.Creator
public Event[] newArray(int i) {
return new Event[i];
}
};
private String category;
private Map<String, String> customSegmentation;
private long duration;
private String eventId;
private long recordedAt;
private Map<String, String> segmentation;
private String userId;
private String version;
public static class Builder {
private String a;
private String b;
private String c;
private String d;
private long e;
private long f = System.currentTimeMillis() / 1000;
private Map<String, String> g;
private Map<String, String> h;
public Builder(String str, String str2) {
this.a = str;
this.c = str2;
}
public Builder a(String str) {
this.b = str;
return this;
}
public Builder b(String str) {
this.d = str;
return this;
}
public String toString() {
return "Event.Builder{eventId='" + this.a + "', userId='" + this.b + "', category='" + this.c + "', version='" + this.d + "', duration=" + this.e + ", recordedAt=" + this.f + ", segmentation=" + this.g + ", customSegmentation=" + this.h + '}';
}
public Builder a(long j) {
this.e = j;
return this;
}
public Builder b(long j) {
this.f = j / 1000;
return this;
}
public Builder a(Map<String, String> map) {
this.h = map;
return this;
}
public Builder b(Map<String, String> map) {
this.g = map;
return this;
}
public Event a() {
Event event = new Event(this.a, this.c);
event.userId = this.b;
event.version = this.d;
event.duration = this.e;
event.recordedAt = this.f;
Map map = this.g;
if (map == null) {
map = new HashMap();
}
event.segmentation = map;
Map map2 = this.h;
if (map2 == null) {
map2 = new HashMap();
}
event.customSegmentation = map2;
return event;
}
}
@Override // android.os.Parcelable
public int describeContents() {
return 0;
}
public String getCategory() {
return this.category;
}
public Map<String, String> getCustomSegmentation() {
return this.customSegmentation;
}
public long getDuration() {
return this.duration;
}
public String getEventId() {
return this.eventId;
}
public long getRecordedAt() {
return this.recordedAt;
}
public Map<String, String> getSegmentation() {
return this.segmentation;
}
public String getUserId() {
return this.userId;
}
public String getVersion() {
return this.version;
}
public String toString() {
return "Event{eventId='" + this.eventId + "', userId='" + this.userId + "', category='" + this.category + "', version='" + this.version + "', duration=" + this.duration + ", recordedAt=" + this.recordedAt + ", segmentation=" + this.segmentation + ", customSegmentation=" + this.customSegmentation + '}';
}
@Override // android.os.Parcelable
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(this.eventId);
parcel.writeString(this.userId);
parcel.writeString(this.category);
parcel.writeString(this.version);
parcel.writeLong(this.duration);
parcel.writeLong(this.recordedAt);
parcel.writeByte((byte) (this.segmentation == null ? 0 : 1));
Map<String, String> map = this.segmentation;
if (map != null) {
parcel.writeMap(map);
}
parcel.writeByte((byte) (this.customSegmentation != null ? 1 : 0));
Map<String, String> map2 = this.customSegmentation;
if (map2 != null) {
parcel.writeMap(map2);
}
}
private Event(String str, String str2) {
this.eventId = str;
this.category = str2;
}
private Event(Parcel parcel) {
this.eventId = parcel.readString();
this.userId = parcel.readString();
this.category = parcel.readString();
this.version = parcel.readString();
this.duration = parcel.readLong();
this.recordedAt = parcel.readLong();
if (parcel.readByte() != 0) {
this.segmentation = new HashMap();
parcel.readMap(this.segmentation, String.class.getClassLoader());
}
if (parcel.readByte() != 0) {
this.customSegmentation = new HashMap();
parcel.readMap(this.customSegmentation, String.class.getClassLoader());
}
}
}

View File

@@ -0,0 +1,5 @@
package com.ubtrobot.analytics;
/* loaded from: classes2.dex */
public interface EventReporter {
}

View File

@@ -0,0 +1,167 @@
package com.ubtrobot.analytics;
import android.database.Cursor;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.ubt.jimu.controller.data.widget.JockstickDataConverter;
import com.ubtrobot.analytics.Event;
import com.unity3d.ads.metadata.MediationMetaData;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/* loaded from: classes2.dex */
public class EventScheme {
public static void a(AnalyticsDBHelper analyticsDBHelper) {
Log.i("dance", "Create table: event");
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("CREATE TABLE IF NOT EXISTS ");
stringBuffer.append("event");
stringBuffer.append("(");
stringBuffer.append(JockstickDataConverter.ID);
stringBuffer.append(" INTEGER PRIMARY KEY AUTOINCREMENT,");
stringBuffer.append("event_id");
stringBuffer.append(" VARCHAR NOT NULL,");
stringBuffer.append("user_id");
stringBuffer.append(" VARCHAR DEFAULT '',");
stringBuffer.append("duration");
stringBuffer.append(" INTEGER DEFAULT 0,");
stringBuffer.append("category");
stringBuffer.append(" VARCHAR(32) NOT NULL,");
stringBuffer.append(MediationMetaData.KEY_VERSION);
stringBuffer.append(" VARCHAR(32) DEFAULT '',");
stringBuffer.append("recorded_at");
stringBuffer.append(" INTEGER DEFAULT 0,");
stringBuffer.append("segmentation");
stringBuffer.append(" VARCHAR DEFAULT '',");
stringBuffer.append("custom_segmentation");
stringBuffer.append(" VARCHAR DEFAULT ''");
stringBuffer.append(")");
analyticsDBHelper.a(stringBuffer.toString());
}
public static void b(AnalyticsDBHelper analyticsDBHelper) {
Log.i("dance", "Running upgradeToVersion2 ...");
if (analyticsDBHelper.a("event", "duration")) {
return;
}
analyticsDBHelper.b(String.format("ALTER TABLE %s ADD COLUMN %s INTEGER DEFAULT 0", "event", "duration"));
}
public static void c(AnalyticsDBHelper analyticsDBHelper) {
Log.i("dance", "Running upgradeToVersion3 ...");
if (analyticsDBHelper.a("event", "user_id")) {
return;
}
analyticsDBHelper.b(String.format("ALTER TABLE %s ADD COLUMN %s VARCHAR DEFAULT ''", "event", "user_id"));
}
public static void d(AnalyticsDBHelper analyticsDBHelper) {
Log.i("dance", "Running upgradeToVersion4 ...");
if (analyticsDBHelper.a("event", MediationMetaData.KEY_VERSION)) {
return;
}
analyticsDBHelper.b(String.format("ALTER TABLE %s ADD COLUMN %s VARCHAR DEFAULT ''", "event", MediationMetaData.KEY_VERSION));
}
public static class Converters {
private static final Gson a = new Gson();
static String a(List<Event> list) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("INSERT INTO ");
stringBuffer.append("event");
stringBuffer.append("(");
stringBuffer.append("event_id");
stringBuffer.append(", ");
stringBuffer.append("user_id");
stringBuffer.append(", ");
stringBuffer.append("category");
stringBuffer.append(", ");
stringBuffer.append(MediationMetaData.KEY_VERSION);
stringBuffer.append(", ");
stringBuffer.append("duration");
stringBuffer.append(", ");
stringBuffer.append("recorded_at");
stringBuffer.append(", ");
stringBuffer.append("segmentation");
stringBuffer.append(", ");
stringBuffer.append("custom_segmentation");
stringBuffer.append(") ");
stringBuffer.append("values");
StringBuffer stringBuffer2 = new StringBuffer();
for (Event event : list) {
String userId = event.getUserId();
String str = "";
if (userId == null) {
userId = "";
}
String version = event.getVersion();
if (version != null) {
str = version;
}
stringBuffer2.append("(");
stringBuffer2.append("'");
stringBuffer2.append(event.getEventId());
stringBuffer2.append("', ");
stringBuffer2.append("'");
stringBuffer2.append(userId);
stringBuffer2.append("', ");
stringBuffer2.append("'");
stringBuffer2.append(event.getCategory());
stringBuffer2.append("', ");
stringBuffer2.append("'");
stringBuffer2.append(str);
stringBuffer2.append("', ");
stringBuffer2.append("'");
stringBuffer2.append(event.getDuration());
stringBuffer2.append("', ");
stringBuffer2.append("'");
stringBuffer2.append(event.getRecordedAt());
stringBuffer2.append("', ");
stringBuffer2.append("'");
stringBuffer2.append(a.toJson(event.getSegmentation()));
stringBuffer2.append("', ");
stringBuffer2.append("'");
stringBuffer2.append(a.toJson(event.getCustomSegmentation()));
stringBuffer2.append("'");
stringBuffer2.append(")");
stringBuffer2.append(", ");
}
stringBuffer2.delete(stringBuffer2.length() - 2, stringBuffer2.length() - 1);
stringBuffer.append(stringBuffer2.toString());
return stringBuffer.toString();
}
static Event a(Cursor cursor) {
String string = cursor.getString(cursor.getColumnIndex("event_id"));
String string2 = cursor.getString(cursor.getColumnIndex("user_id"));
String string3 = cursor.getString(cursor.getColumnIndex("category"));
String string4 = cursor.getString(cursor.getColumnIndex(MediationMetaData.KEY_VERSION));
long j = cursor.getLong(cursor.getColumnIndex("duration"));
long j2 = cursor.getLong(cursor.getColumnIndex("recorded_at"));
String string5 = cursor.getString(cursor.getColumnIndex("segmentation"));
String string6 = cursor.getString(cursor.getColumnIndex("custom_segmentation"));
Event.Builder builder = new Event.Builder(string, string3);
builder.a(string2);
builder.b(string4);
builder.a(j);
builder.b(j2 * 1000);
builder.b(a(string5));
builder.a(a(string6));
return builder.a();
}
private static Map<String, String> a(String str) {
try {
return (Map) a.fromJson(str, new TypeToken<Map<String, String>>() { // from class: com.ubtrobot.analytics.EventScheme.Converters.1
}.getType());
} catch (JsonSyntaxException unused) {
Log.e("dance", "Converters to map failed:" + str);
return new HashMap();
}
}
}
}

View File

@@ -0,0 +1,19 @@
package com.ubtrobot.analytics;
import java.io.IOException;
import java.util.List;
/* loaded from: classes2.dex */
public interface EventStorage {
int a() throws IOException;
List<Event> a(int i) throws IOException;
void a(Event event) throws IOException;
void a(List<Event> list) throws IOException;
void b(int i) throws IOException;
void b(List<Event> list) throws IOException;
}

View File

@@ -0,0 +1,164 @@
package com.ubtrobot.analytics;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import com.google.gson.Gson;
import com.ubtrobot.analytics.ReportException;
import com.ubtrobot.analytics.device.DeviceInfo;
import com.ubtrobot.analytics.device.DeviceInfoReporter;
import com.ubtrobot.analytics.device.MobileDeviceInfo;
import com.ubtrobot.analytics.device.RobotDeviceInfo;
import com.ubtrobot.http.rest.URestException;
import com.ubtrobot.okhttp.interceptor.sign.AuthorizationInterceptor;
import com.ubtrobot.okhttp.interceptor.sign.HttpSignInterceptor;
import com.ubtrobot.retrofit.adapter.urest.URestCall;
import com.ubtrobot.retrofit.adapter.urest.URestCallAdapterFactory;
import java.util.List;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
/* loaded from: classes2.dex */
public class HttpReport implements EventReporter, DeviceInfoReporter {
private final Context a;
private final String b;
private final String c;
private final String d;
private ReportService e;
public interface ReportService {
@GET("configuration/realtime/eventIds")
URestCall<RealtimeEvent> getForthwithEventIdList(@Query("eventCode") String str);
@POST("collected/device")
URestCall<Void> reportDeviceInfo(@Body MobileDeviceInfo mobileDeviceInfo);
@POST("collected/device")
URestCall<Void> reportDeviceInfo(@Body RobotDeviceInfo robotDeviceInfo);
@POST("collected/events")
URestCall<Void> reportEvent(@Body List<Event> list);
}
public HttpReport(Context context, String str, String str2, String str3) {
this.a = context;
this.b = str;
this.c = str2;
if (str3 == null || str3.length() == 0) {
throw new IllegalArgumentException("deviceId is not null.");
}
this.d = str3;
b();
}
private void b() {
this.e = b("https://apis.ubtrobot.com/v1/collect-rest/");
}
private void a() {
this.e = b("https://test79.ubtrobot.com/v1/collect-rest/");
}
private ReportService b(String str) {
Log.i("Analytics", "Url:" + str);
return (ReportService) new Retrofit.Builder().client(new OkHttpClient.Builder().addInterceptor(new HttpSignInterceptor(this.b, this.c, new HttpSignInterceptor.DeviceInfoSource() { // from class: com.ubtrobot.analytics.HttpReport.2
@Override // com.ubtrobot.okhttp.interceptor.sign.HttpSignInterceptor.DeviceInfoSource
public String a(Request request) {
return HttpReport.this.d;
}
})).addInterceptor(new AuthorizationInterceptor(new AuthorizationInterceptor.AuthenticationInfoSource() { // from class: com.ubtrobot.analytics.HttpReport.1
@Override // com.ubtrobot.okhttp.interceptor.sign.AuthorizationInterceptor.AuthenticationInfoSource
public String a(Request request) {
return HttpReport.this.d;
}
@Override // com.ubtrobot.okhttp.interceptor.sign.AuthorizationInterceptor.AuthenticationInfoSource
public String b(Request request) {
return null;
}
})).build()).addConverterFactory(GsonConverterFactory.create(new Gson())).addCallAdapterFactory(URestCallAdapterFactory.create()).baseUrl(str).build().create(ReportService.class);
}
public void a(boolean z) {
if (z) {
Log.i("Analytics", "Change debug environment.");
a();
} else {
Log.i("Analytics", "Change release environment.");
b();
}
}
public RealtimeEvent a(String str) throws ReportException {
try {
return this.e.getForthwithEventIdList(str).a();
} catch (URestException e) {
Log.e("Analytics", "Get forthwith event id list fail.", e);
a(e);
throw null;
} catch (IllegalStateException e2) {
Log.e("Analytics", "Method getRealtimeEventIdList fail.", e2);
return null;
}
}
public void a(List<Event> list) throws ReportException {
try {
Log.i("Analytics", "Start report event:" + list.size());
this.e.reportEvent(list).a();
} catch (URestException e) {
a(e);
throw null;
}
}
private void a(URestException uRestException) throws ReportException {
int code = uRestException.getCode();
if (code == -3) {
throw ReportException.Factory.c(uRestException);
}
if (code == -2) {
if (a(this.a)) {
throw ReportException.Factory.b(uRestException);
}
throw ReportException.Factory.a(uRestException);
}
if (code == -1) {
throw new IllegalStateException("Should add permission(android.permission.INTERNET).", uRestException);
}
if (code != 1001) {
throw ReportException.Factory.a(uRestException);
}
throw ReportException.Factory.d(uRestException);
}
private boolean a(Context context) {
NetworkInfo activeNetworkInfo = ((ConnectivityManager) context.getSystemService("connectivity")).getActiveNetworkInfo();
if (activeNetworkInfo == null) {
return false;
}
return activeNetworkInfo.isConnected();
}
public void a(DeviceInfo deviceInfo) throws ReportException {
try {
if (deviceInfo instanceof MobileDeviceInfo) {
this.e.reportDeviceInfo((MobileDeviceInfo) deviceInfo).a();
} else if (deviceInfo instanceof RobotDeviceInfo) {
this.e.reportDeviceInfo((RobotDeviceInfo) deviceInfo).a();
}
} catch (URestException e) {
a(e);
throw null;
} catch (IncompatibleClassChangeError e2) {
Log.e("Analytics", "Method reportDeviceInfo fail", e2);
}
}
}

View File

@@ -0,0 +1,73 @@
package com.ubtrobot.analytics;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/* loaded from: classes2.dex */
public class MemoryEventStorage implements EventStorage {
private final LinkedList<Event> a;
private final int b;
public MemoryEventStorage() {
this(17895697);
}
@Override // com.ubtrobot.analytics.EventStorage
public void a(Event event) throws IOException {
synchronized (this.a) {
this.a.add(event);
}
}
@Override // com.ubtrobot.analytics.EventStorage
public void b(List<Event> list) throws IOException {
synchronized (this.a) {
this.a.addAll(list);
if (this.a.size() <= this.b) {
return;
}
b(this.a.size() - this.b);
}
}
public MemoryEventStorage(int i) {
this.a = new LinkedList<>();
this.b = i;
}
@Override // com.ubtrobot.analytics.EventStorage
public int a() throws IOException {
int size;
synchronized (this.a) {
size = this.a.size();
}
return size;
}
@Override // com.ubtrobot.analytics.EventStorage
public List<Event> a(int i) throws IOException {
LinkedList linkedList;
synchronized (this.a) {
linkedList = new LinkedList(this.a.subList(0, Math.min(i, this.a.size())));
}
return linkedList;
}
@Override // com.ubtrobot.analytics.EventStorage
public void b(int i) throws IOException {
synchronized (this.a) {
Iterator<Event> it = this.a.iterator();
for (int i2 = 0; it.hasNext() && i2 < i; i2++) {
it.next();
it.remove();
}
}
}
@Override // com.ubtrobot.analytics.EventStorage
public void a(List<Event> list) throws IOException {
throw new IllegalStateException("MemoryEventStorage nonsupport removeEvents(List<Event>).");
}
}

View File

@@ -0,0 +1,56 @@
package com.ubtrobot.analytics;
import android.os.Parcel;
import android.os.Parcelable;
/* loaded from: classes2.dex */
public class ModuleVersion implements Parcelable {
public static final Parcelable.Creator<ModuleVersion> CREATOR = new Parcelable.Creator<ModuleVersion>() { // from class: com.ubtrobot.analytics.ModuleVersion.1
/* JADX WARN: Can't rename method to resolve collision */
@Override // android.os.Parcelable.Creator
public ModuleVersion createFromParcel(Parcel parcel) {
return new ModuleVersion(parcel);
}
/* JADX WARN: Can't rename method to resolve collision */
@Override // android.os.Parcelable.Creator
public ModuleVersion[] newArray(int i) {
return new ModuleVersion[i];
}
};
private String name;
private String version;
@Override // android.os.Parcelable
public int describeContents() {
return 0;
}
public String getName() {
return this.name;
}
public String getVersion() {
return this.version;
}
public String toString() {
return "ModuleVersion{name='" + this.name + "', version='" + this.version + "'}";
}
@Override // android.os.Parcelable
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(this.name);
parcel.writeString(this.version);
}
public ModuleVersion(String str, String str2) {
this.name = str;
this.version = str2;
}
private ModuleVersion(Parcel parcel) {
this.name = parcel.readString();
this.version = parcel.readString();
}
}

View File

@@ -0,0 +1,37 @@
package com.ubtrobot.analytics;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
/* loaded from: classes2.dex */
public class NetWorkChangeReceiver extends BroadcastReceiver {
private INetWorkChange a;
public interface INetWorkChange {
void a();
}
public NetWorkChangeReceiver(INetWorkChange iNetWorkChange) {
this.a = iNetWorkChange;
}
@Override // android.content.BroadcastReceiver
public void onReceive(Context context, Intent intent) {
Log.i("Analytics", "Action: " + intent.getAction());
if ("android.net.conn.CONNECTIVITY_CHANGE".equals(intent.getAction())) {
NetworkInfo activeNetworkInfo = ((ConnectivityManager) context.getSystemService("connectivity")).getActiveNetworkInfo();
if (activeNetworkInfo == null) {
Log.w("Analytics", "NetworkInfo get fail.");
} else if (NetworkInfo.State.CONNECTED != activeNetworkInfo.getState() || !activeNetworkInfo.isConnected()) {
Log.w("Analytics", "NetWork is not connect.");
} else {
Log.i("Analytics", "NetWork is connected.");
this.a.a();
}
}
}
}

View File

@@ -0,0 +1,27 @@
package com.ubtrobot.analytics;
import java.util.Collections;
import java.util.List;
/* loaded from: classes2.dex */
public class RealtimeEvent {
private String a;
private List<String> b;
private RealtimeEvent() {
}
public String a() {
String str = this.a;
return str != null ? str : "";
}
public List<String> b() {
List<String> list = this.b;
return list != null ? list : Collections.emptyList();
}
public String toString() {
return "RealtimeEvent{eventCode='" + this.a + "', eventIdList=" + this.b + '}';
}
}

View File

@@ -0,0 +1,49 @@
package com.ubtrobot.analytics;
/* loaded from: classes2.dex */
public class ReportException extends Exception {
private static final int CODE_INTERNAL_SERVER_ERROR = 2;
private static final int CODE_NETWORK_DISCONNECTED = 1;
private static final int CODE_TIMEOUT = 3;
private static final int CODE_UNAUTHORIZED = 4;
private final int code;
public static class Factory {
public static ReportException a(Throwable th) {
return new ReportException(2, "Can not connect the server or unauthorized key.", th);
}
public static ReportException b(Throwable th) {
return new ReportException(1, "Network disconnected.", th);
}
public static ReportException c(Throwable th) {
return new ReportException(3, "Report timeout.", th);
}
public static ReportException d(Throwable th) {
return new ReportException(4, "unauthorized key.", th);
}
}
public boolean causedByInternalServerError() {
return this.code == 2;
}
public boolean causedByNetworkDisconnected() {
return this.code == 1;
}
public boolean causedByTimeOut() {
return this.code == 3;
}
public boolean causedByUnauthorized() {
return this.code == 4;
}
private ReportException(int i, String str, Throwable th) {
super(str, th);
this.code = i;
}
}

View File

@@ -0,0 +1,54 @@
package com.ubtrobot.analytics;
import android.os.Handler;
/* loaded from: classes2.dex */
public class Retry {
private int a;
private RetryRunnable b;
private Handler c;
private RetryListener d;
public interface RetryListener {
void a();
}
private class RetryRunnable implements Runnable {
private RetryRunnable() {
}
@Override // java.lang.Runnable
public void run() {
Retry.this.d.a();
Retry.this.c.postDelayed(this, (long) (Math.pow(2.0d, Retry.this.a) * 1000.0d));
Retry.c(Retry.this);
Retry retry = Retry.this;
retry.a = retry.a > 32 ? 0 : Retry.this.a;
}
}
public Retry(RetryListener retryListener) {
if (retryListener == null) {
throw new IllegalArgumentException("Argument retryListener is null.");
}
this.d = retryListener;
this.b = new RetryRunnable();
this.c = new Handler();
}
static /* synthetic */ int c(Retry retry) {
int i = retry.a;
retry.a = i + 1;
return i;
}
public void b() {
this.c.removeCallbacks(this.b);
}
public void a() {
this.a = 0;
this.c.removeCallbacks(this.b);
this.c.post(this.b);
}
}

View File

@@ -0,0 +1,65 @@
package com.ubtrobot.analytics;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.concurrent.TimeUnit;
/* loaded from: classes2.dex */
public class Strategy implements Parcelable {
private static final int MIN_REPORT_INTERVAL_MINUTE = 1;
private long reportIntervalSeconds;
public static final Strategy DEFAULT = new Builder().a();
private static final long DEFAULT_REPORT_INTERVAL_SECONDS = TimeUnit.MINUTES.toSeconds(5);
public static final Parcelable.Creator<Strategy> CREATOR = new Parcelable.Creator<Strategy>() { // from class: com.ubtrobot.analytics.Strategy.1
/* JADX WARN: Can't rename method to resolve collision */
@Override // android.os.Parcelable.Creator
public Strategy createFromParcel(Parcel parcel) {
return new Strategy(parcel);
}
/* JADX WARN: Can't rename method to resolve collision */
@Override // android.os.Parcelable.Creator
public Strategy[] newArray(int i) {
return new Strategy[i];
}
};
public static class Builder {
private long a = Strategy.DEFAULT_REPORT_INTERVAL_SECONDS;
public Strategy a() {
Strategy strategy = new Strategy();
strategy.reportIntervalSeconds = this.a;
return strategy;
}
public String toString() {
return "Builder{reportIntervalSeconds=" + this.a + '}';
}
}
@Override // android.os.Parcelable
public int describeContents() {
return 0;
}
public long getReportIntervalSeconds() {
return this.reportIntervalSeconds;
}
public String toString() {
return "Strategy{reportIntervalSeconds=" + this.reportIntervalSeconds + '}';
}
@Override // android.os.Parcelable
public void writeToParcel(Parcel parcel, int i) {
parcel.writeLong(this.reportIntervalSeconds);
}
private Strategy() {
}
private Strategy(Parcel parcel) {
this.reportIntervalSeconds = parcel.readLong();
}
}

View File

@@ -0,0 +1,5 @@
package com.ubtrobot.analytics.device;
/* loaded from: classes2.dex */
public interface DeviceInfo {
}

View File

@@ -0,0 +1,5 @@
package com.ubtrobot.analytics.device;
/* loaded from: classes2.dex */
public interface DeviceInfoReporter {
}

View File

@@ -0,0 +1,236 @@
package com.ubtrobot.analytics.device;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import com.ijm.dataencryption.de.DataDecryptTool;
import com.ubt.jimu.diy.model.CategoryModel;
import com.ubt.jimu.diy.view.fragment.BuildStepFragment;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Locale;
import java.util.TimeZone;
import java.util.UUID;
/* loaded from: classes2.dex */
public class DeviceInfoUtils {
private static final byte[] a = new byte[0];
private static volatile String b;
public static String a() {
return Locale.getDefault().getLanguage();
}
public static String b() {
return Build.MODEL;
}
public static String c() {
return Build.VERSION.RELEASE;
}
public static String d(Context context) {
try {
return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException unused) {
Log.w("Analytics", "Get app version fail.");
return "";
}
}
public static String e() {
try {
return TimeZone.getDefault().getDisplayName(false, 0);
} catch (AssertionError unused) {
Log.w("Analytics", "Fail get time zone.");
String date = new Date(119, 5, 9).toString();
return date.substring(20, date.length() - 5);
}
}
@SuppressLint({"MissingPermission"})
private static String f(Context context) {
String imei;
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService("phone");
if (telephonyManager != null) {
try {
imei = Build.VERSION.SDK_INT >= 26 ? telephonyManager.getImei() : telephonyManager.getDeviceId();
} catch (SecurityException unused) {
}
return (imei != null || "000000000000000".equals(imei)) ? "" : imei;
}
imei = null;
if (imei != null) {
}
}
private static String g(Context context) {
String macAddress;
if (Build.VERSION.SDK_INT >= 23) {
macAddress = g();
if (TextUtils.isEmpty(macAddress)) {
macAddress = f();
}
} else {
macAddress = ((WifiManager) context.getSystemService("wifi")).getConnectionInfo().getMacAddress();
}
return (macAddress == null || "02:00:00:00:00:00".equals(macAddress)) ? "" : macAddress;
}
public static String h(Context context) {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService("phone");
return telephonyManager != null ? telephonyManager.getSimOperator() : "";
}
private static String i(Context context) {
if (b != null) {
return b;
}
synchronized (a) {
if (b != null) {
return b;
}
String j = j(context);
if (j.length() == 0) {
j = a(context);
}
b = j;
return b;
}
}
private static String j(Context context) {
return context.getApplicationContext().getSharedPreferences("deviceId", 0).getString(BuildStepFragment.UUID, "");
}
private static String a(Context context) {
String b2 = b(b(context));
a(context, b2);
return b2;
}
private static String b(String str) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(str.getBytes());
return new BigInteger(1, messageDigest.digest()).toString(16);
} catch (NoSuchAlgorithmException unused) {
throw new IllegalStateException("MessageDigest md5 fail.");
}
}
private static String c(Context context) {
String string = Settings.Secure.getString(context.getContentResolver(), "android_id");
return (string == null || "9774d56d682e549c".equals(string)) ? "" : string;
}
private static void a(Context context, String str) {
SharedPreferences.Editor edit = context.getApplicationContext().getSharedPreferences("deviceId", 0).edit();
edit.putString(BuildStepFragment.UUID, str);
edit.apply();
}
@SuppressLint({"MissingPermission"})
private static String d() {
try {
String serial = Build.VERSION.SDK_INT >= 26 ? Build.getSerial() : Build.SERIAL;
return CategoryModel.unknown.equals(serial.toLowerCase()) ? "" : serial;
} catch (SecurityException unused) {
Log.i("Analytics", "Get sn is not permission.");
return "";
}
}
private static String f() {
for (String str : new String[]{"/sys/class/net/wlan0/address", "/sys/class/net/eth0/address", "/sys/devices/virtual/net/wlan0/address"}) {
String a2 = a(str);
if (a2.length() > 0) {
return a2;
}
}
return "";
}
private static String b(Context context) {
String g = g(context);
String c = c(context);
String f = f(context);
String d = d();
StringBuffer stringBuffer = new StringBuffer();
if (g.length() != 0) {
stringBuffer.append(g);
}
if (c.length() != 0) {
stringBuffer.append(c);
}
if (f.length() != 0) {
stringBuffer.append(f);
}
if (d.length() != 0) {
stringBuffer.append(d);
}
if (stringBuffer.length() == 0) {
stringBuffer.append(UUID.randomUUID().toString().replace("-", ""));
}
return stringBuffer.toString();
}
public static String e(Context context) {
return i(context);
}
private static String g() {
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
if (!networkInterfaces.hasMoreElements()) {
return "";
}
NetworkInterface nextElement = networkInterfaces.nextElement();
String name = nextElement.getName();
if (!"wlan0".equals(name) && !"eth0".equals(name)) {
return "";
}
try {
byte[] hardwareAddress = nextElement.getHardwareAddress();
StringBuilder sb = new StringBuilder();
for (byte b2 : hardwareAddress) {
sb.append(String.format("%02X:", Byte.valueOf(b2)));
}
sb.deleteCharAt(sb.length() - 1);
return sb.toString().toLowerCase(Locale.getDefault());
} catch (SocketException unused) {
return "";
}
} catch (SocketException unused2) {
Log.w("Analytics", "Get Enumeration fail.");
return "";
}
}
private static String a(String str) {
String str2 = "";
try {
FileReader fileReader = new FileReader(str);
str2 = new BufferedReader(fileReader, DataDecryptTool.DECRYPT_SP_FILE).readLine();
fileReader.close();
} catch (FileNotFoundException | IOException unused) {
}
return str2;
}
}

View File

@@ -0,0 +1,114 @@
package com.ubtrobot.analytics.device;
import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;
/* loaded from: classes2.dex */
public class MobileDeviceInfo implements DeviceInfo, Parcelable {
public static final Parcelable.Creator<MobileDeviceInfo> CREATOR = new Parcelable.Creator<MobileDeviceInfo>() { // from class: com.ubtrobot.analytics.device.MobileDeviceInfo.1
/* JADX WARN: Can't rename method to resolve collision */
@Override // android.os.Parcelable.Creator
public MobileDeviceInfo createFromParcel(Parcel parcel) {
return new MobileDeviceInfo(parcel);
}
/* JADX WARN: Can't rename method to resolve collision */
@Override // android.os.Parcelable.Creator
public MobileDeviceInfo[] newArray(int i) {
return new MobileDeviceInfo[i];
}
};
private static final String TAG = "Analytics";
private String appVersion;
private String channel;
private String language;
private String model;
private String osVersion;
private String simOperator;
private String timezone;
private String userId;
@Override // android.os.Parcelable
public int describeContents() {
return 0;
}
public String getAppVersion() {
return this.appVersion;
}
public String getChannel() {
return this.channel;
}
public String getLanguage() {
return this.language;
}
public String getModel() {
return this.model;
}
public String getOsVersion() {
return this.osVersion;
}
public String getSimOperator() {
return this.simOperator;
}
public String getTimezone() {
return this.timezone;
}
public String getUserId() {
return this.userId;
}
public MobileDeviceInfo setChannel(String str) {
this.channel = str;
return this;
}
public MobileDeviceInfo setUserId(String str) {
this.userId = str;
return this;
}
public String toString() {
return "MobileDeviceInfo{model='" + this.model + "', osVersion='" + this.osVersion + "', language='" + this.language + "', timezone='" + this.timezone + "', appVersion='" + this.appVersion + "', userId='" + this.userId + "', channel='" + this.channel + "', simOperator='" + this.simOperator + "'}";
}
@Override // android.os.Parcelable
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(this.model);
parcel.writeString(this.osVersion);
parcel.writeString(this.language);
parcel.writeString(this.timezone);
parcel.writeString(this.appVersion);
parcel.writeString(this.userId);
parcel.writeString(this.channel);
parcel.writeString(this.simOperator);
}
public MobileDeviceInfo(Context context) {
this.model = DeviceInfoUtils.b();
this.osVersion = DeviceInfoUtils.c();
this.language = DeviceInfoUtils.a();
this.timezone = DeviceInfoUtils.e();
this.appVersion = DeviceInfoUtils.d(context);
this.simOperator = DeviceInfoUtils.h(context);
}
private MobileDeviceInfo(Parcel parcel) {
this.model = parcel.readString();
this.osVersion = parcel.readString();
this.language = parcel.readString();
this.timezone = parcel.readString();
this.appVersion = parcel.readString();
this.userId = parcel.readString();
this.channel = parcel.readString();
this.simOperator = parcel.readString();
}
}

View File

@@ -0,0 +1,106 @@
package com.ubtrobot.analytics.device;
import android.os.Parcel;
import android.os.Parcelable;
import com.ubtrobot.analytics.ModuleVersion;
import java.util.List;
/* loaded from: classes2.dex */
public class RobotDeviceInfo implements DeviceInfo, Parcelable {
public static final Parcelable.Creator<RobotDeviceInfo> CREATOR = new Parcelable.Creator<RobotDeviceInfo>() { // from class: com.ubtrobot.analytics.device.RobotDeviceInfo.1
/* JADX WARN: Can't rename method to resolve collision */
@Override // android.os.Parcelable.Creator
public RobotDeviceInfo createFromParcel(Parcel parcel) {
return new RobotDeviceInfo(parcel);
}
/* JADX WARN: Can't rename method to resolve collision */
@Override // android.os.Parcelable.Creator
public RobotDeviceInfo[] newArray(int i) {
return new RobotDeviceInfo[i];
}
};
private String channel;
private String language;
private String model;
private List<ModuleVersion> moduleVersions;
private String osVersion;
private String timezone;
private String userId;
public RobotDeviceInfo(List<ModuleVersion> list) {
this.model = DeviceInfoUtils.b();
this.osVersion = DeviceInfoUtils.c();
this.language = DeviceInfoUtils.a();
this.timezone = DeviceInfoUtils.e();
this.moduleVersions = list;
}
@Override // android.os.Parcelable
public int describeContents() {
return 0;
}
public String getChannel() {
return this.channel;
}
public String getLanguage() {
return this.language;
}
public String getModel() {
return this.model;
}
public List<ModuleVersion> getModuleVersions() {
return this.moduleVersions;
}
public String getOsVersion() {
return this.osVersion;
}
public String getTimezone() {
return this.timezone;
}
public String getUserId() {
return this.userId;
}
public RobotDeviceInfo setChannel(String str) {
this.channel = str;
return this;
}
public RobotDeviceInfo setUserId(String str) {
this.userId = str;
return this;
}
public String toString() {
return "RobotDeviceInfo{model='" + this.model + "', osVersion='" + this.osVersion + "', language='" + this.language + "', timezone='" + this.timezone + "', moduleVersions=" + this.moduleVersions + ", userId='" + this.userId + "', channel='" + this.channel + "'}";
}
@Override // android.os.Parcelable
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(this.model);
parcel.writeString(this.osVersion);
parcel.writeString(this.language);
parcel.writeString(this.timezone);
parcel.writeTypedList(this.moduleVersions);
parcel.writeString(this.userId);
parcel.writeString(this.channel);
}
protected RobotDeviceInfo(Parcel parcel) {
this.model = parcel.readString();
this.osVersion = parcel.readString();
this.language = parcel.readString();
this.timezone = parcel.readString();
this.moduleVersions = parcel.createTypedArrayList(ModuleVersion.CREATOR);
this.userId = parcel.readString();
this.channel = parcel.readString();
}
}

View File

@@ -0,0 +1,12 @@
package com.ubtrobot.analytics.event;
import com.ubtrobot.analytics.Event;
import java.io.IOException;
import java.util.List;
/* loaded from: classes2.dex */
public interface ActivenessEventSource {
int a(int i) throws IOException;
List<Event> a() throws IOException;
}

View File

@@ -0,0 +1,214 @@
package com.ubtrobot.analytics.event;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import com.ubtrobot.analytics.ActivenessRecord;
import com.ubtrobot.analytics.ActivenessStorage;
import com.ubtrobot.analytics.Event;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
/* loaded from: classes2.dex */
public class AppActivenessEventSource implements ActivenessEventSource, Application.ActivityLifecycleCallbacks {
private static final long i = TimeUnit.SECONDS.toMillis(60);
private Ticker b;
private Executor c;
private String d;
private String e;
private ActivenessStorage g;
private final long a = TimeUnit.SECONDS.toMillis(15);
private long f = System.currentTimeMillis();
private AppTicktockListener h = new AppTicktockListener();
private class AppTicktockListener implements TicktockListener {
private long a;
private long b;
private long c;
static /* synthetic */ AppTicktockListener a(AppTicktockListener appTicktockListener, long j) {
appTicktockListener.c(j);
return appTicktockListener;
}
static /* synthetic */ AppTicktockListener b(AppTicktockListener appTicktockListener, long j) {
appTicktockListener.b(j);
return appTicktockListener;
}
private AppTicktockListener() {
this.a = System.currentTimeMillis();
}
/* JADX INFO: Access modifiers changed from: private */
public void d(long j) {
this.c += j;
AppActivenessEventSource.this.c.execute(new Runnable() { // from class: com.ubtrobot.analytics.event.AppActivenessEventSource.AppTicktockListener.2
@Override // java.lang.Runnable
public void run() {
try {
AppActivenessEventSource.this.g.b(AppTicktockListener.this.a(0L));
} catch (IOException unused) {
}
}
});
}
private AppTicktockListener b(long j) {
this.c = j;
return this;
}
private AppTicktockListener c(long j) {
this.a = j;
return this;
}
@Override // com.ubtrobot.analytics.event.TicktockListener
public void a() {
AppActivenessEventSource.this.c.execute(new Runnable() { // from class: com.ubtrobot.analytics.event.AppActivenessEventSource.AppTicktockListener.1
@Override // java.lang.Runnable
public void run() {
try {
AppActivenessEventSource.this.g.b(AppTicktockListener.this.a(AppActivenessEventSource.this.a));
} catch (IOException unused) {
}
}
});
}
/* JADX INFO: Access modifiers changed from: private */
public ActivenessRecord a(long j) {
this.b = System.currentTimeMillis();
this.c += j;
ActivenessRecord activenessRecord = new ActivenessRecord("app_activeness");
activenessRecord.a(AppActivenessEventSource.this.d);
activenessRecord.b(AppActivenessEventSource.this.e);
activenessRecord.b(this.a);
activenessRecord.c(this.b);
activenessRecord.a(this.c);
return activenessRecord;
}
/* JADX INFO: Access modifiers changed from: private */
public long b() {
return this.b;
}
/* JADX INFO: Access modifiers changed from: private */
public void c() {
AppActivenessEventSource.this.c.execute(new Runnable() { // from class: com.ubtrobot.analytics.event.AppActivenessEventSource.AppTicktockListener.3
@Override // java.lang.Runnable
public void run() {
try {
AppActivenessEventSource.this.g.a(AppTicktockListener.this.a(0L));
} catch (IOException unused) {
}
}
});
}
}
public AppActivenessEventSource(Context context, Ticker ticker, Executor executor) {
this.b = ticker;
this.c = executor;
this.g = new ActivenessStorage(context);
b();
}
@Override // android.app.Application.ActivityLifecycleCallbacks
public void onActivityCreated(Activity activity, Bundle bundle) {
}
@Override // android.app.Application.ActivityLifecycleCallbacks
public void onActivityDestroyed(Activity activity) {
}
@Override // android.app.Application.ActivityLifecycleCallbacks
public void onActivityPaused(Activity activity) {
}
@Override // android.app.Application.ActivityLifecycleCallbacks
public void onActivityResumed(Activity activity) {
c();
this.f = System.currentTimeMillis();
if (Math.abs(this.f - this.h.b()) < i) {
return;
}
AppTicktockListener appTicktockListener = this.h;
AppTicktockListener.a(appTicktockListener, this.f);
AppTicktockListener.b(appTicktockListener, 0 - this.a);
appTicktockListener.c();
}
@Override // android.app.Application.ActivityLifecycleCallbacks
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
@Override // android.app.Application.ActivityLifecycleCallbacks
public void onActivityStarted(Activity activity) {
}
@Override // android.app.Application.ActivityLifecycleCallbacks
public void onActivityStopped(Activity activity) {
d();
this.h.d(System.currentTimeMillis() - this.f);
}
private void b() {
this.c.execute(new Runnable() { // from class: com.ubtrobot.analytics.event.AppActivenessEventSource.1
@Override // java.lang.Runnable
public void run() {
try {
AppActivenessEventSource.this.g.a();
} catch (IOException e) {
Log.e("Analytics", "Execute delete repetition sql fail.", e);
}
}
});
}
private void c() {
AppTicktockListener appTicktockListener = this.h;
AppTicktockListener.b(appTicktockListener, appTicktockListener.c - this.a);
this.b.a(this.h, 15, TimeUnit.SECONDS);
}
private void d() {
this.b.a();
}
public void a(String str) {
this.e = str;
}
@Override // com.ubtrobot.analytics.event.ActivenessEventSource
public List<Event> a() throws IOException {
LinkedList linkedList = new LinkedList();
for (ActivenessRecord activenessRecord : this.g.a("app_activeness")) {
if (Math.abs(System.currentTimeMillis() - activenessRecord.d()) >= i) {
HashMap hashMap = new HashMap();
hashMap.put("startTime", String.valueOf(activenessRecord.c()));
Event.Builder builder = new Event.Builder("app_activeness", "predefined_event");
builder.a(activenessRecord.e());
builder.b(activenessRecord.f());
builder.b(hashMap);
builder.b(activenessRecord.d());
builder.a(activenessRecord.a());
linkedList.add(builder.a());
}
}
return linkedList;
}
@Override // com.ubtrobot.analytics.event.ActivenessEventSource
public int a(int i2) throws IOException {
return this.g.a("app_activeness", i2);
}
}

View File

@@ -0,0 +1,42 @@
package com.ubtrobot.analytics.event;
import android.os.Handler;
import android.os.Looper;
import java.util.concurrent.TimeUnit;
/* loaded from: classes2.dex */
public class Ticker {
private Handler a = new Handler(Looper.getMainLooper());
private ListenerRunnable b;
private class ListenerRunnable implements Runnable {
private TicktockListener a;
private int b;
private TimeUnit c;
public ListenerRunnable(TicktockListener ticktockListener, int i, TimeUnit timeUnit) {
this.a = ticktockListener;
this.b = i;
this.c = timeUnit;
}
@Override // java.lang.Runnable
public void run() {
this.a.a();
Ticker.this.a.postDelayed(this, this.c.toMillis(this.b));
}
}
public void a(TicktockListener ticktockListener, int i, TimeUnit timeUnit) {
ListenerRunnable listenerRunnable = this.b;
if (listenerRunnable == null) {
listenerRunnable = new ListenerRunnable(ticktockListener, i, timeUnit);
}
this.b = listenerRunnable;
this.a.post(this.b);
}
public void a() {
this.a.removeCallbacks(this.b);
}
}

View File

@@ -0,0 +1,6 @@
package com.ubtrobot.analytics.event;
/* loaded from: classes2.dex */
public interface TicktockListener {
void a();
}

View File

@@ -0,0 +1,167 @@
package com.ubtrobot.analytics.mobile;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageManager;
import android.util.Log;
import com.ubtrobot.analytics.AnalyticsServiceImpl;
import com.ubtrobot.analytics.Event;
import com.ubtrobot.analytics.device.DeviceInfoUtils;
import com.ubtrobot.analytics.device.MobileDeviceInfo;
import com.ubtrobot.analytics.event.AppActivenessEventSource;
import com.ubtrobot.analytics.event.Ticker;
import com.unity3d.ads.metadata.MediationMetaData;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
/* loaded from: classes2.dex */
public class AnalyticsKit {
private static volatile Context a;
private static volatile String b;
private static volatile AppActivenessEventSource c;
private static volatile AnalyticsServiceImpl d;
private static String e;
private AnalyticsKit() {
}
public static void a(Context context, String str, String str2, String str3, Executor executor) {
if (context == null) {
throw new IllegalArgumentException("Context is null.");
}
a("appId", str);
a("appKey", str2);
if (str3 == null || str3.isEmpty()) {
str3 = DeviceInfoUtils.e(context);
}
String str4 = str3;
if (d != null) {
return;
}
synchronized (AnalyticsKit.class) {
if (d != null) {
return;
}
a = context.getApplicationContext();
b = a(a);
if (executor == null) {
executor = Executors.newSingleThreadExecutor();
}
Executor executor2 = executor;
c = new AppActivenessEventSource(a, new Ticker(), executor2);
c.a(b);
d = new AnalyticsServiceImpl(a, str, str2, str4, c, executor2);
((Application) a).registerActivityLifecycleCallbacks(c);
}
}
public static void b(boolean z) {
a();
d.b(z);
}
public static void c(String str, String str2) {
d.a(new MobileDeviceInfo(a).setUserId(str).setChannel(str2));
}
public static void d(String str) {
if (str == null || str.isEmpty()) {
throw new IllegalArgumentException("Argument viewName is null or isEmpty.");
}
b("page_end", b(str, "view"));
}
public static void e(String str) {
if (str == null || str.isEmpty()) {
throw new IllegalArgumentException("Argument viewName is null or isEmpty.");
}
b("page_start", b(str, "view"));
}
public static void b(String str, long j, Map<String, String> map) {
if (str == null || str.length() <= 0 || str.length() > 64) {
throw new IllegalArgumentException("Argument need 0 < eventId.length <= 64.");
}
if (j >= 0) {
a(str, j, map);
return;
}
throw new IllegalArgumentException("Argument duration < 0.");
}
public static void c(String str) {
a(str, 0L);
}
public static void b(String str) {
a("activityName", str);
b("page_start", b(str, "activity"));
}
private static void b(String str, Map<String, String> map) {
a();
Event.Builder builder = new Event.Builder(str, "predefined_event");
builder.b(map);
builder.a(e);
builder.b(b);
d.a(builder.a());
}
private static String a(Context context) {
try {
return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException unused) {
Log.w("Analytics", "Get app version fail.");
return "";
}
}
private static Map<String, String> b(String str, String str2) {
HashMap hashMap = new HashMap();
hashMap.put("type", str2);
hashMap.put(MediationMetaData.KEY_NAME, str);
return hashMap;
}
private static void a(String str, String str2) {
if (str2 == null || str2.length() <= 0) {
throw new IllegalArgumentException("Argument:" + str + " is null.");
}
}
private static void a() {
if (d == null) {
throw new IllegalStateException("Please call com.ubtrobot.analytics.mobile.AnalyticsKit.initialize");
}
}
public static void a(boolean z) {
a();
d.a(z);
}
public static void a(String str, long j) {
b(str, j, null);
}
public static void a(String str, Map<String, String> map) {
b(str, 0L, map);
}
private static void a(String str, long j, Map<String, String> map) {
a();
Event.Builder builder = new Event.Builder(str, "custom_event");
builder.a(j);
builder.a(map);
builder.a(e);
builder.b(b);
d.a(builder.a());
}
public static void a(String str) {
a("activityName", str);
b("page_end", b(str, "activity"));
}
}

View File

@@ -0,0 +1,19 @@
package com.ubtrobot.http.rest;
/* loaded from: classes2.dex */
public class URestException extends Exception {
private final int code;
public URestException(int i, String str) {
this(i, str, null);
}
public int getCode() {
return this.code;
}
public URestException(int i, String str, Throwable th) {
super(str, th);
this.code = i;
}
}

View File

@@ -0,0 +1,42 @@
package com.ubtrobot.jimu;
/* loaded from: classes2.dex */
public class Firmware {
private String a;
private String b;
private String c;
private int d;
private boolean e;
public Firmware(int i, String str, String str2, String str3, int i2, boolean z) {
this.e = false;
this.d = i;
this.a = str;
this.b = str2;
this.c = str3;
this.e = z;
}
public String a() {
return this.c;
}
public void a(int i) {
}
public String b() {
return this.b;
}
public int c() {
return this.d;
}
public String d() {
return this.a;
}
public boolean e() {
return this.e;
}
}

View File

@@ -0,0 +1,8 @@
package com.ubtrobot.jimu.bluetooth;
/* loaded from: classes2.dex */
public interface Cancellable {
boolean cancel();
boolean isCancelled();
}

View File

@@ -0,0 +1,8 @@
package com.ubtrobot.jimu.bluetooth;
/* loaded from: classes2.dex */
public interface ConnectCallback {
void a(int i, String str);
void onSuccess();
}

View File

@@ -0,0 +1,9 @@
package com.ubtrobot.jimu.bluetooth;
/* loaded from: classes2.dex */
public enum ConnectionState {
STATE_CONNECTING,
STATE_CONNECTED,
STATE_DISCONNECTING,
STATE_DISCONNECTED
}

View File

@@ -0,0 +1,6 @@
package com.ubtrobot.jimu.bluetooth;
/* loaded from: classes2.dex */
public interface ConnectionStateListener {
void onConnectionStateChange(String str, ConnectionState connectionState);
}

View File

@@ -0,0 +1,6 @@
package com.ubtrobot.jimu.bluetooth;
/* loaded from: classes2.dex */
public interface DataReceiveListener {
void onDataAvailable(String str, byte b, byte[] bArr);
}

View File

@@ -0,0 +1,257 @@
package com.ubtrobot.jimu.bluetooth;
import android.content.Context;
import android.util.Log;
import com.ubtrobot.jimu.bluetooth.base.discover.ScanResult;
import com.ubtrobot.jimu.bluetooth.base.discover.ScannedHubEmitter;
import com.ubtrobot.jimu.bluetooth.proxy.BluetoothProxy;
import com.ubtrobot.jimu.bluetooth.proxy.DeviceListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
/* loaded from: classes2.dex */
public class JimuBluetoothManager {
private static final String k = "JimuBluetoothManager";
/* renamed from: a */
private Context context;
/* renamed from: b */
private BluetoothProxy bluetoothProxy;
/* renamed from: c */
private List<ConnectionStateListener> connectionStateListeners;
/* renamed from: d */
private List<DataReceiveListener> dataReceiveListeners;
/* renamed from: e */
private HashMap<String, ConnectCallback> connectionCallbacks;
/* renamed from: f */
private HashMap<String, ConnectionState> connectionStates;
/* renamed from: g */
private boolean supportsBluetooth;
/* renamed from: h */
private String macAddress;
private String i;
/* renamed from: j */
private DeviceListener deviceListener;
private static class Holder {
private static final JimuBluetoothManager a = new JimuBluetoothManager();
}
private JimuBluetoothManager() {
this.connectionStateListeners = new ArrayList();
this.dataReceiveListeners = new ArrayList();
this.connectionCallbacks = new HashMap<>();
this.connectionStates = new HashMap<>();
this.supportsBluetooth = false;
this.macAddress = null;
this.i = null;
this.deviceListener = new DeviceListener() { // from class: com.ubtrobot.jimu.bluetooth.JimuBluetoothManager.1
@Override // com.ubtrobot.jimu.bluetooth.proxy.DeviceListener
/* renamed from: a */
public void onConnectState(boolean isSuccess, String macAddress) {
ConnectionState connectionState;
Log.d(JimuBluetoothManager.k, "onConnectState isSuccess:" + isSuccess + " mac:" + macAddress);
if (macAddress == null) {
Log.e(JimuBluetoothManager.k, "onConnectState isSuccess:" + isSuccess + " mac:" + macAddress);
if (JimuBluetoothManager.this.i == null) {
return;
} else {
macAddress = JimuBluetoothManager.this.i;
}
}
if (isSuccess) {
connectionState = ConnectionState.STATE_CONNECTED;
JimuBluetoothManager.this.macAddress = macAddress;
} else {
connectionState = ConnectionState.STATE_DISCONNECTED;
if (macAddress.equals(JimuBluetoothManager.this.macAddress)) {
JimuBluetoothManager.this.macAddress = null;
}
}
JimuBluetoothManager.this.a(macAddress, connectionState);
ConnectCallback connectCallback = (ConnectCallback) JimuBluetoothManager.this.connectionCallbacks.get(macAddress);
if (connectCallback != null) {
if (isSuccess) {
connectCallback.onSuccess();
} else {
connectCallback.a(-1, "connect fail!");
}
}
}
@Override // com.ubtrobot.jimu.bluetooth.proxy.DeviceListener
public String b(String str) {
return null;
}
@Override // com.ubtrobot.jimu.bluetooth.proxy.DeviceListener
public void a(String str, byte b, byte[] bArr, int i) {
Iterator it = JimuBluetoothManager.this.dataReceiveListeners.iterator();
while (it.hasNext()) {
((DataReceiveListener) it.next()).onDataAvailable(str, b, bArr);
}
}
@Override // com.ubtrobot.jimu.bluetooth.proxy.DeviceListener
/* renamed from: a */
public void disconnect(String macAddress) {
JimuBluetoothManager.this.a(macAddress, ConnectionState.STATE_DISCONNECTED);
if (macAddress.equals(JimuBluetoothManager.this.macAddress)) {
JimuBluetoothManager.this.macAddress = null;
}
}
};
this.bluetoothProxy = BluetoothProxy.c();
}
public static JimuBluetoothManager d() {
return Holder.a;
}
public void b(ConnectionStateListener connectionStateListener) {
synchronized (this.connectionStateListeners) {
this.connectionStateListeners.remove(connectionStateListener);
}
}
/* JADX INFO: Access modifiers changed from: private */
public void a(String macAddress, ConnectionState connectionState) {
synchronized (this.connectionStateListeners) {
Iterator<ConnectionStateListener> it = this.connectionStateListeners.iterator();
while (true) {
if (!it.hasNext()) {
break;
}
ConnectionStateListener next = it.next();
ConnectionState connectionState2 = this.connectionStates.get(macAddress);
if (connectionState2 == null) {
connectionState2 = ConnectionState.STATE_DISCONNECTED;
}
if (connectionState2 == connectionState) {
Log.w(k, "new connection state is same to old state, not notify connectionstate change.");
break;
}
next.onConnectionStateChange(macAddress, connectionState);
}
this.connectionStates.put(macAddress, connectionState);
}
}
/* renamed from: b */
public void removeDataReceiveListener(DataReceiveListener dataReceiveListener) {
this.dataReceiveListeners.remove(dataReceiveListener);
}
/* JADX INFO: Access modifiers changed from: private */
/* renamed from: b */
public boolean isJimu(String str) {
String lowerCase = str.toLowerCase();
if (lowerCase.startsWith("My_Jimu_".toLowerCase())) {
return true;
}
return lowerCase.startsWith("Jimu".toLowerCase()) && !lowerCase.startsWith("Jimuspk".toLowerCase());
}
public String b() {
return this.macAddress;
}
/* renamed from: a */
public boolean supportsBluetooth(Context context) {
this.context = context.getApplicationContext();
this.supportsBluetooth = this.bluetoothProxy.a(this.context, this.deviceListener);
boolean supportsBluetooth = this.supportsBluetooth;
if (supportsBluetooth) {
return supportsBluetooth;
}
Log.e(k, "Device not support bluetooth or not bluetooth related permissions");
return false;
}
/* renamed from: a */
public void connectWithCallback(String macAddress, ConnectCallback connectCallback) {
this.i = macAddress;
this.connectionStates.get(macAddress);
this.connectionCallbacks.put(macAddress, connectCallback);
this.connectionStates.put(macAddress, ConnectionState.STATE_CONNECTING);
this.bluetoothProxy.a(macAddress);
}
/* renamed from: a */
public void disconnect() {
Log.i(k, "Disconnect buletooth.");
this.macAddress = null;
this.bluetoothProxy.a();
this.connectionStates.clear();
}
public void a(ConnectionStateListener connectionStateListener) {
synchronized (this.connectionStateListeners) {
if (!this.connectionStateListeners.contains(connectionStateListener)) {
this.connectionStateListeners.add(connectionStateListener);
}
}
}
/* renamed from: a */
public ConnectionState getConnectionState(String macAddress) {
if (macAddress == null) {
return ConnectionState.STATE_DISCONNECTED;
}
ConnectionState connectionState = this.connectionStates.get(macAddress);
return connectionState == null ? ConnectionState.STATE_DISCONNECTED : connectionState;
}
public synchronized void a(String str, int i, byte[] bArr) {
this.bluetoothProxy.a(str, (byte) i, bArr, bArr.length);
}
public void a(DataReceiveListener dataReceiveListener) {
if (this.dataReceiveListeners.contains(dataReceiveListener)) {
return;
}
this.dataReceiveListeners.add(dataReceiveListener);
}
public Cancellable a(final ScannedHubEmitter scannedHubEmitter, int i) {
if (!this.supportsBluetooth) {
Log.e(k, "Bluetooth is not support!");
scannedHubEmitter.a(4, "Scan fail as bluetooth is not support");
return null;
}
return this.bluetoothProxy.a(new ScannedHubEmitter() { // from class: com.ubtrobot.jimu.bluetooth.JimuBluetoothManager.2
@Override // com.ubtrobot.jimu.bluetooth.base.discover.ScannedHubEmitter
public void a(ScanResult scanResult) {
String name;
if (scanResult == null || scanResult.a() == null || (name = scanResult.a().getName()) == null || !JimuBluetoothManager.this.isJimu(name)) {
return;
}
scannedHubEmitter.a(scanResult);
}
@Override // com.ubtrobot.jimu.bluetooth.base.discover.ScannedHubEmitter
public void a(int i2, String str) {
scannedHubEmitter.a(i2, str);
}
@Override // com.ubtrobot.jimu.bluetooth.base.discover.ScannedHubEmitter
public void a() {
scannedHubEmitter.a();
}
}, i);
}
public void a(String str, boolean z) {
this.bluetoothProxy.a(str, z);
}
}

View File

@@ -0,0 +1,18 @@
package com.ubtrobot.jimu.bluetooth;
/* loaded from: classes2.dex */
public enum RobotWalkingType {
DOUBLE_FEET("doubleFeet"),
FOUR_FEET("fourFeet"),
WHEEL_MODE("wheelMode");
private String type;
RobotWalkingType(String str) {
this.type = str;
}
public String getType() {
return this.type;
}
}

View File

@@ -0,0 +1,13 @@
package com.ubtrobot.jimu.bluetooth.base;
/* compiled from: DeviceProcessThread.java */
/* loaded from: classes2.dex */
class BUFFER_DATA {
public byte[] a;
public int b;
public long c;
public int d;
BUFFER_DATA() {
}
}

View File

@@ -0,0 +1,177 @@
package com.ubtrobot.jimu.bluetooth.base;
import android.bluetooth.BluetoothSocket;
import android.os.SystemClock;
import android.util.Log;
import com.ijm.dataencryption.de.DataDecryptTool;
import com.ubtrobot.jimu.bluetooth.base.DeviceProcessThread;
import com.ubtrobot.jimu.bluetooth.utils.ByteHexHelper;
import com.ubtrobot.log.ALog;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/* loaded from: classes2.dex */
public class BlueToothClientHandler extends Thread implements DeviceProcessThread.DeviceProcessThreadCallBack {
private final String a;
private final BluetoothSocket b;
private final InputStream c;
private final OutputStream d;
private final ClentCallBack e;
private ProtocolPacket g;
private DeviceProcessThread k;
private int l;
private int m;
private boolean f = true;
private boolean j = true;
private long h = SystemClock.uptimeMillis();
private long i = this.h;
public interface ClentCallBack {
void a(String str);
void a(String str, byte b, byte[] bArr, int i);
}
public BlueToothClientHandler(String str, BluetoothSocket bluetoothSocket, ClentCallBack clentCallBack) {
InputStream inputStream;
this.l = 0;
this.m = 0;
this.a = str;
this.b = bluetoothSocket;
this.e = clentCallBack;
OutputStream outputStream = null;
try {
inputStream = bluetoothSocket.getInputStream();
try {
outputStream = bluetoothSocket.getOutputStream();
} catch (IOException e) {
e = e;
Log.e("BlueToothClientHandler", "temp sockets not created", e);
this.c = inputStream;
this.d = outputStream;
this.l = 0;
this.m = 0;
this.g = new ProtocolPacket();
this.k = new DeviceProcessThread(this);
this.k.start();
}
} catch (IOException e2) {
e = e2;
inputStream = null;
}
this.c = inputStream;
this.d = outputStream;
this.l = 0;
this.m = 0;
this.g = new ProtocolPacket();
this.k = new DeviceProcessThread(this);
this.k.start();
}
public String a() {
return this.a;
}
public void b(byte[] bArr, int i) {
this.k.a(bArr, i);
}
public void c(byte[] bArr, int i) {
if (SystemClock.uptimeMillis() - this.i < 3000) {
return;
}
if (!this.j) {
this.h = SystemClock.uptimeMillis();
} else {
a(bArr, i);
this.l++;
}
}
@Override // java.lang.Thread, java.lang.Runnable
public void run() {
byte[] bArr = new byte[DataDecryptTool.DECRYPT_SP_FILE];
while (this.f) {
try {
int read = this.c.read(bArr);
if (read > 0) {
byte[] bArr2 = new byte[read];
System.arraycopy(bArr, 0, bArr2, 0, read);
ALog.a("DV_READSTATUS").d("Receive: param=" + ByteHexHelper.a(bArr2));
for (int i = 0; i < read; i++) {
if (this.g.b(bArr[i])) {
if (this.e != null) {
this.g.a(this.g.g().length);
this.e.a(this.a, this.g.f(), this.g.g(), this.g.a());
}
this.l = 0;
this.m = 0;
this.h = SystemClock.uptimeMillis();
this.k.a(this.g.f());
}
}
}
} catch (IOException e) {
Log.e("BlueToothClientHandler", "read form bt socket fail", e);
return;
} catch (Exception unused) {
this.f = false;
return;
}
}
}
public void a(boolean z) {
this.j = z;
}
public void b() {
synchronized (this) {
try {
this.l = 0;
this.m = 0;
this.f = false;
if (this.k != null) {
this.k.a();
}
if (this.c != null) {
this.c.close();
}
if (this.d != null) {
this.d.close();
}
if (this.b != null) {
this.b.close();
}
if (this.e != null) {
this.e.a(this.a);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override // com.ubtrobot.jimu.bluetooth.base.DeviceProcessThread.DeviceProcessThreadCallBack
public synchronized void a(byte[] bArr, int i) {
try {
try {
ALog.a("DV_READSTATUS").d("SendData=" + ByteHexHelper.a(bArr));
this.d.write(bArr, 0, i);
this.i = SystemClock.uptimeMillis();
this.m = this.m + 1;
} catch (Exception e) {
ALog.a("BlueToothClientHandler").d("Send bluetooth data to socket fail! Close socket!", e);
b();
}
} catch (IOException e2) {
ALog.a("BlueToothClientHandler").d("Send bluetooth data to socket fail! Close socket!", e2);
b();
}
}
public boolean c() {
return (this.f && isAlive() && (!(this.l > 3 || this.m > 6) || !this.j)) ? false : true;
}
}

View File

@@ -0,0 +1,168 @@
package com.ubtrobot.jimu.bluetooth.base;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.SystemClock;
import com.ubtrobot.jimu.bluetooth.base.BlueToothClientHandler;
import com.ubtrobot.jimu.bluetooth.base.BluetoothUtil;
import com.ubtrobot.jimu.bluetooth.proxy.Callback;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/* loaded from: classes2.dex */
public class BlueToothManager extends Thread implements BlueToothClientHandler.ClentCallBack, BluetoothUtil.BluetoothUtilCallBack {
private Callback d;
private BluetoothUtil e;
private boolean a = false;
private boolean c = true;
private List<BlueToothClientHandler> b = new ArrayList();
public BlueToothManager(Context context, Callback callback) {
this.d = callback;
this.e = new BluetoothUtil(context, this);
SystemClock.uptimeMillis();
}
public void a(BluetoothDevice bluetoothDevice) {
b();
this.e.a(bluetoothDevice);
}
@Override // com.ubtrobot.jimu.bluetooth.base.BluetoothUtil.BluetoothUtilCallBack
public void a(String str, int i) {
}
public synchronized BlueToothClientHandler b(String str) {
BlueToothClientHandler blueToothClientHandler;
blueToothClientHandler = null;
Iterator<BlueToothClientHandler> it = this.b.iterator();
while (true) {
if (!it.hasNext()) {
break;
}
BlueToothClientHandler next = it.next();
if (next.a().equals(str)) {
blueToothClientHandler = next;
break;
}
}
return blueToothClientHandler;
}
public void c() {
this.c = true;
this.e.a(this.a);
start();
}
@Override // java.lang.Thread, java.lang.Runnable
public void run() {
BlueToothClientHandler blueToothClientHandler;
while (this.c) {
synchronized (this) {
Iterator<BlueToothClientHandler> it = this.b.iterator();
while (true) {
if (!it.hasNext()) {
blueToothClientHandler = null;
break;
}
blueToothClientHandler = it.next();
if (blueToothClientHandler.c()) {
break;
}
ProtocolPacket protocolPacket = new ProtocolPacket();
protocolPacket.a((byte) 3);
protocolPacket.a((byte[]) null);
protocolPacket.a(0);
byte[] b = protocolPacket.b();
blueToothClientHandler.c(b, b.length);
}
if (blueToothClientHandler != null) {
String a = blueToothClientHandler.a();
blueToothClientHandler.b();
this.b.remove(blueToothClientHandler);
if (this.d != null) {
this.d.b(a);
}
} else {
try {
Thread.sleep(300L);
} catch (InterruptedException unused) {
this.c = false;
Thread.currentThread().interrupt();
return;
}
}
}
}
}
public void a(String str, boolean z) {
BlueToothClientHandler b = b(str);
if (b != null) {
b.a(z);
}
}
public synchronized void b(String str, BluetoothSocket bluetoothSocket) {
if (b(str) != null) {
return;
}
BlueToothClientHandler blueToothClientHandler = new BlueToothClientHandler(str, bluetoothSocket, this);
this.b.add(blueToothClientHandler);
blueToothClientHandler.start();
}
@Override // com.ubtrobot.jimu.bluetooth.base.BlueToothClientHandler.ClentCallBack
public synchronized void a(String str, byte b, byte[] bArr, int i) {
if (this.d != null) {
this.d.b(str, b, bArr, i);
}
}
@Override // com.ubtrobot.jimu.bluetooth.base.BlueToothClientHandler.ClentCallBack
public synchronized void a(String str) {
if (this.d != null) {
this.d.b(str);
}
}
public synchronized void b() {
if (this.b != null) {
Iterator<BlueToothClientHandler> it = this.b.iterator();
while (it.hasNext()) {
it.next().b();
}
this.b.clear();
}
}
@Override // com.ubtrobot.jimu.bluetooth.base.BluetoothUtil.BluetoothUtilCallBack
public synchronized void a(String str, BluetoothSocket bluetoothSocket) {
b(str, bluetoothSocket);
if (this.d != null) {
this.d.a(true, str);
}
}
@Override // com.ubtrobot.jimu.bluetooth.base.BluetoothUtil.BluetoothUtilCallBack
public synchronized void a() {
if (this.d != null) {
this.d.a(false, null);
}
}
public synchronized void b(String str, byte b, byte[] bArr, int i) {
ProtocolPacket protocolPacket = new ProtocolPacket();
protocolPacket.a(b);
protocolPacket.a(bArr);
protocolPacket.a(i);
byte[] b2 = protocolPacket.b();
BlueToothClientHandler b3 = b(str);
if (b3 != null) {
b3.b(b2, b2.length);
}
}
}

View File

@@ -0,0 +1,231 @@
package com.ubtrobot.jimu.bluetooth.base;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import com.ubtrobot.jimu.bluetooth.Cancellable;
import com.ubtrobot.jimu.bluetooth.base.discover.ScanResult;
import com.ubtrobot.jimu.bluetooth.base.discover.ScannedHubEmitter;
import com.ubtrobot.jimu.bluetooth.proxy.Callback;
import com.ubtrobot.jimu.bluetooth.proxy.Device;
import com.ubtrobot.jimu.bluetooth.proxy.DeviceListener;
import com.ubtrobot.jimu.bluetooth.proxy.Proxy;
import com.ubtrobot.log.ALog;
import java.util.ArrayList;
/* loaded from: classes2.dex */
public class BluetoothLib extends Callback implements Proxy {
private static final String k = "BluetoothLib";
public static BluetoothLib l;
public static BlueToothManager m;
private BluetoothAdapter b;
private Context c;
private ArrayList<String> d = new ArrayList<>();
private Boolean e;
private DeviceListener f;
private ScannedHubEmitter g;
private Handler h;
private Cancellable i;
private final BroadcastReceiver j;
public BluetoothLib() {
new ArrayList();
this.e = false;
new Runnable(this) { // from class: com.ubtrobot.jimu.bluetooth.base.BluetoothLib.1
@Override // java.lang.Runnable
public void run() {
}
};
this.i = new Cancellable() { // from class: com.ubtrobot.jimu.bluetooth.base.BluetoothLib.3
@Override // com.ubtrobot.jimu.bluetooth.Cancellable
public boolean cancel() {
BluetoothLib.this.c();
BluetoothLib.this.h.removeCallbacksAndMessages(null);
return BluetoothLib.this.b != null && BluetoothLib.this.b.isDiscovering();
}
@Override // com.ubtrobot.jimu.bluetooth.Cancellable
public boolean isCancelled() {
return BluetoothLib.this.b != null && BluetoothLib.this.b.isDiscovering();
}
};
this.j = new BroadcastReceiver() { // from class: com.ubtrobot.jimu.bluetooth.base.BluetoothLib.4
@Override // android.content.BroadcastReceiver
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (!"android.bluetooth.device.action.FOUND".equals(action)) {
"android.bluetooth.adapter.action.DISCOVERY_FINISHED".equals(action);
return;
}
BluetoothDevice bluetoothDevice = (BluetoothDevice) intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
if (bluetoothDevice == null || intent.getExtras() == null) {
return;
}
short s = intent.getExtras().getShort("android.bluetooth.device.extra.RSSI");
String replace = TextUtils.isEmpty(bluetoothDevice.getName()) ? "" : bluetoothDevice.getName().replace("\n", "").replace("\\n", "");
String str = replace + "\n" + bluetoothDevice.getAddress() + "\n" + ((int) s);
if (BluetoothLib.this.c(str)) {
return;
}
BluetoothLib.this.d.add(str);
BluetoothLib.this.f.b(str);
Proxy.a.add(new Device(bluetoothDevice.getAddress(), replace));
if (!TextUtils.isEmpty(bluetoothDevice.getName()) && bluetoothDevice.getName().toLowerCase().contains("jimu")) {
ScanResult scanResult = new ScanResult(bluetoothDevice, s);
if (BluetoothLib.this.g != null) {
BluetoothLib.this.g.a(scanResult);
}
}
}
};
}
public static synchronized BluetoothLib d() {
BluetoothLib bluetoothLib;
synchronized (BluetoothLib.class) {
if (l == null) {
synchronized (BluetoothLib.class) {
if (l == null) {
l = new BluetoothLib();
}
}
}
bluetoothLib = l;
}
return bluetoothLib;
}
private void e() {
if (this.e.booleanValue()) {
return;
}
this.c.registerReceiver(this.j, new IntentFilter("android.bluetooth.device.action.FOUND"));
this.c.registerReceiver(this.j, new IntentFilter("android.bluetooth.adapter.action.DISCOVERY_FINISHED"));
this.e = true;
}
public void b() {
ALog.a(k).d("startScan");
BluetoothAdapter bluetoothAdapter = this.b;
if (bluetoothAdapter == null) {
return;
}
try {
if (bluetoothAdapter.isDiscovering()) {
this.b.cancelDiscovery();
}
this.d.clear();
this.b.startDiscovery();
} catch (Exception e) {
Log.e(k, "Start scan fail", e);
}
}
public void c() {
BluetoothAdapter bluetoothAdapter = this.b;
if (bluetoothAdapter == null || !bluetoothAdapter.isDiscovering()) {
return;
}
this.b.cancelDiscovery();
}
@Override // com.ubtrobot.jimu.bluetooth.proxy.Proxy
public boolean a(Context context, DeviceListener deviceListener) {
this.c = context;
this.f = deviceListener;
if (m == null) {
m = new BlueToothManager(context, this);
m.c();
}
this.b = BluetoothAdapter.getDefaultAdapter();
if (this.b == null) {
return false;
}
e();
Log.i(k, "BluetoothLib-init");
this.h = new Handler(context.getMainLooper());
return true;
}
/* JADX INFO: Access modifiers changed from: private */
public boolean c(String str) {
for (int i = 0; i < this.d.size(); i++) {
if (this.d.get(i).equals(str)) {
return true;
}
}
return false;
}
@Override // com.ubtrobot.jimu.bluetooth.proxy.Callback
public void b(String str, byte b, byte[] bArr, int i) {
this.f.a(str, b, bArr, i);
}
@Override // com.ubtrobot.jimu.bluetooth.proxy.Callback
public void b(String str) {
this.f.disconnect(str);
}
public Cancellable a(final ScannedHubEmitter scannedHubEmitter, int i) {
BluetoothAdapter bluetoothAdapter = this.b;
if (bluetoothAdapter == null) {
scannedHubEmitter.a(-2, "Device not support bluetooth!");
return null;
}
if (bluetoothAdapter.getState() != 12) {
scannedHubEmitter.a(-3, "Bluetooth is not turn on!");
return null;
}
this.g = scannedHubEmitter;
b();
this.h.postDelayed(new Runnable() { // from class: com.ubtrobot.jimu.bluetooth.base.BluetoothLib.2
@Override // java.lang.Runnable
public void run() {
BluetoothLib.this.c();
scannedHubEmitter.a();
}
}, i);
return this.i;
}
@Override // com.ubtrobot.jimu.bluetooth.proxy.Proxy
public void a(String str) {
BluetoothAdapter bluetoothAdapter = this.b;
if (bluetoothAdapter == null) {
return;
}
if (bluetoothAdapter.isDiscovering()) {
this.b.cancelDiscovery();
}
BluetoothDevice remoteDevice = this.b.getRemoteDevice(str);
m.b();
m.a(remoteDevice);
}
@Override // com.ubtrobot.jimu.bluetooth.proxy.Proxy
public void a() {
m.b();
}
@Override // com.ubtrobot.jimu.bluetooth.proxy.Proxy
public void a(String str, byte b, byte[] bArr, int i) {
m.b(str, b, bArr, i);
}
@Override // com.ubtrobot.jimu.bluetooth.proxy.Proxy
public void a(String str, boolean z) {
m.a(str, z);
}
@Override // com.ubtrobot.jimu.bluetooth.proxy.Callback
public void a(boolean z, String str) {
this.f.onConnectState(z, str);
}
}

View File

@@ -0,0 +1,245 @@
package com.ubtrobot.jimu.bluetooth.base;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.util.Log;
import com.ubtrobot.log.ALog;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.UUID;
/* loaded from: classes2.dex */
public class BluetoothUtil {
private static final UUID i = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private AcceptThread b;
private ConnectThread c;
private String e;
private final BluetoothUtilCallBack g;
private BluetoothDevice h;
private boolean f = false;
private final BluetoothAdapter a = BluetoothAdapter.getDefaultAdapter();
private int d = 0;
private class AcceptThread extends Thread {
private final BluetoothServerSocket a;
private boolean b = true;
public AcceptThread() {
BluetoothServerSocket bluetoothServerSocket;
try {
bluetoothServerSocket = BluetoothUtil.this.a.listenUsingRfcommWithServiceRecord("BluetoothChat", BluetoothUtil.i);
} catch (IOException e) {
Log.e("BluetoothChatService", "listen() failed", e);
bluetoothServerSocket = null;
}
this.a = bluetoothServerSocket;
}
public void cancel() {
ALog.a("BluetoothChatService").d("cancel " + this);
try {
this.b = false;
this.a.close();
} catch (IOException e) {
ALog.a("BluetoothChatService").d("close() of server failed", e);
}
}
@Override // java.lang.Thread, java.lang.Runnable
public void run() {
ALog.a("BluetoothChatService").d("BEGIN mAcceptThread" + this);
setName("AcceptThread");
while (this.b) {
try {
BluetoothSocket accept = this.a.accept();
if (accept != null) {
BluetoothUtil.this.a(accept, accept.getRemoteDevice());
}
} catch (IOException e) {
Log.e("BluetoothChatService", "accept() failed", e);
}
}
Log.i("BluetoothChatService", "END mAcceptThread");
}
}
class BluetoothThread extends Thread {
BluetoothThread() {
}
@Override // java.lang.Thread, java.lang.Runnable
public void run() {
if (BluetoothUtil.this.c != null) {
BluetoothUtil.this.c.cancel();
BluetoothUtil.this.c = null;
try {
Thread.sleep(500L);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
BluetoothUtil bluetoothUtil = BluetoothUtil.this;
bluetoothUtil.c = bluetoothUtil.new ConnectThread(bluetoothUtil.h);
BluetoothUtil.this.c.start();
BluetoothUtil.this.a(2);
}
}
public interface BluetoothUtilCallBack {
void a();
void a(String str, int i);
void a(String str, BluetoothSocket bluetoothSocket);
}
private class ConnectThread extends Thread {
private BluetoothSocket a;
private final BluetoothDevice b;
@SuppressLint({"NewApi"})
public ConnectThread(BluetoothDevice bluetoothDevice) {
this.b = bluetoothDevice;
BluetoothSocket bluetoothSocket = null;
try {
if (DeviceDependency.a()) {
try {
try {
bluetoothSocket = (BluetoothSocket) bluetoothDevice.getClass().getMethod("createInsecureRfcommSocket", Integer.TYPE).invoke(bluetoothDevice, 6);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SecurityException e2) {
e2.printStackTrace();
} catch (InvocationTargetException e3) {
e3.printStackTrace();
}
} catch (IllegalArgumentException e4) {
e4.printStackTrace();
} catch (NoSuchMethodException e5) {
e5.printStackTrace();
}
} else if (DeviceDependency.b()) {
bluetoothSocket = this.b.createRfcommSocketToServiceRecord(BluetoothUtil.i);
} else {
bluetoothSocket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(BluetoothUtil.i);
Log.v("BluetoothChatService", "createInsecureRfcommSocketToServiceRecord");
}
} catch (IOException e6) {
Log.e("BluetoothChatService", "create() failed", e6);
}
this.a = bluetoothSocket;
}
public void cancel() {
try {
Log.e("zdy", "socket.close()");
if (this.a != null) {
this.a.close();
}
} catch (IOException e) {
Log.e("BluetoothChatService", "close() of connect socket failed", e);
}
}
@Override // java.lang.Thread, java.lang.Runnable
@SuppressLint({"NewApi"})
public void run() {
Log.i("BluetoothChatService", "BEGIN mConnectThread");
setName("ConnectThread");
if (this.a == null) {
Log.w("BluetoothChatService", "get BluetoothSocket fail! Stop connect!");
return;
}
BluetoothUtil.this.a.cancelDiscovery();
try {
Log.e("zdy", "socket.run()");
this.a.connect();
synchronized (BluetoothUtil.this) {
BluetoothUtil.this.c = null;
}
BluetoothUtil.this.a(this.a, this.b);
} catch (Exception e) {
e.printStackTrace();
Log.e("zdy", "IOException", e);
BluetoothUtil.this.b();
try {
this.a.close();
} catch (IOException e2) {
Log.e("BluetoothChatService", "unable to close() socket during connection failure", e2);
} catch (Exception unused) {
Log.e("BluetoothChatService", "unable close socket during connection failure.");
}
}
}
}
public BluetoothUtil(Context context, BluetoothUtilCallBack bluetoothUtilCallBack) {
this.g = bluetoothUtilCallBack;
}
/* JADX INFO: Access modifiers changed from: private */
public void b() {
a(1);
BluetoothUtilCallBack bluetoothUtilCallBack = this.g;
if (bluetoothUtilCallBack != null) {
bluetoothUtilCallBack.a();
}
}
/* JADX INFO: Access modifiers changed from: private */
public synchronized void a(int i2) {
ALog.a("BluetoothChatService").d("setState() " + this.d + " -> " + i2);
this.d = i2;
if (i2 != 3) {
this.e = null;
}
if (this.g != null) {
this.g.a(this.e, i2);
}
}
public synchronized void a(boolean z) {
ALog.a("BluetoothChatService").d("start");
this.f = z;
if (this.c != null) {
this.c.cancel();
this.c = null;
}
if (this.b != null) {
this.b.cancel();
this.b = null;
}
if (this.f) {
this.b = new AcceptThread();
this.b.start();
}
a(1);
}
public synchronized void a(BluetoothDevice bluetoothDevice) {
this.h = bluetoothDevice;
new BluetoothThread().start();
}
public synchronized void a(BluetoothSocket bluetoothSocket, BluetoothDevice bluetoothDevice) {
ALog.a("BluetoothChatService").d("connected");
if (this.c != null) {
this.c.cancel();
this.c = null;
}
if (this.b != null) {
this.b.cancel();
this.b = null;
}
this.e = bluetoothDevice.getAddress();
a(3);
if (this.g != null) {
this.g.a(bluetoothDevice.getAddress(), bluetoothSocket);
}
}
}

View File

@@ -0,0 +1,25 @@
package com.ubtrobot.jimu.bluetooth.base;
import android.os.Build;
import com.baidu.cloud.media.player.BDCloudMediaPlayer;
import com.ubt.jimu.blockly.feature.audio.AndroidManufacturer;
/* loaded from: classes2.dex */
public class DeviceDependency {
public static boolean a() {
if (Build.VERSION.RELEASE.startsWith("4.0.") && (Build.MANUFACTURER.equals("samsung") || Build.MANUFACTURER.equals("HTC"))) {
return true;
}
if (Build.VERSION.RELEASE.startsWith("4.1.") && Build.MANUFACTURER.equals("samsung")) {
return true;
}
return Build.MANUFACTURER.equals(AndroidManufacturer.XIAO_MI) && Build.VERSION.RELEASE.equals(BDCloudMediaPlayer.SDK_VERSION);
}
public static boolean b() {
if (Build.MANUFACTURER.equals(AndroidManufacturer.XIAO_MI) && Build.MODEL.equals("2013022") && Build.VERSION.RELEASE.equals("4.2.1")) {
return true;
}
return Build.MODEL.equals("Lenovo A820");
}
}

View File

@@ -0,0 +1,111 @@
package com.ubtrobot.jimu.bluetooth.base;
import android.os.SystemClock;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/* loaded from: classes2.dex */
public class DeviceProcessThread extends Thread {
private DeviceProcessThreadCallBack a;
private List<BUFFER_DATA> b;
private boolean c = true;
public interface DeviceProcessThreadCallBack {
void a(byte[] bArr, int i);
}
public DeviceProcessThread(DeviceProcessThreadCallBack deviceProcessThreadCallBack) {
this.a = deviceProcessThreadCallBack;
new ProtocolPacket();
this.b = new CopyOnWriteArrayList();
}
public void a(byte[] bArr, int i) {
synchronized (this) {
BUFFER_DATA buffer_data = new BUFFER_DATA();
buffer_data.a = bArr;
buffer_data.b = i;
buffer_data.c = SystemClock.uptimeMillis();
buffer_data.d = 0;
this.b.add(buffer_data);
if (this.a != null) {
this.a.a(bArr, i);
}
}
}
public void b(byte[] bArr, int i) {
synchronized (this) {
if (this.a != null) {
this.a.a(bArr, i);
}
}
}
@Override // java.lang.Thread, java.lang.Runnable
public void run() {
while (this.c) {
synchronized (this) {
BUFFER_DATA buffer_data = null;
Iterator<BUFFER_DATA> it = this.b.iterator();
while (true) {
if (!it.hasNext()) {
break;
}
BUFFER_DATA next = it.next();
if (SystemClock.uptimeMillis() - next.c >= 10000) {
if (next.d >= 2) {
buffer_data = next;
break;
} else {
b(next.a, next.b);
next.c = SystemClock.uptimeMillis();
next.d++;
}
}
}
if (buffer_data != null) {
this.b.remove(buffer_data);
} else {
try {
Thread.sleep(100L);
} catch (InterruptedException unused) {
this.c = false;
Thread.currentThread().interrupt();
return;
}
}
}
}
}
public void a() {
synchronized (this) {
this.c = false;
this.b.clear();
}
}
public void a(byte b) {
synchronized (this) {
ProtocolPacket protocolPacket = new ProtocolPacket();
BUFFER_DATA buffer_data = null;
Iterator<BUFFER_DATA> it = this.b.iterator();
while (true) {
if (!it.hasNext()) {
break;
}
BUFFER_DATA next = it.next();
protocolPacket.b(next.a);
if (protocolPacket.f() == b) {
buffer_data = next;
break;
}
}
if (buffer_data != null) {
this.b.remove(buffer_data);
}
}
}
}

View File

@@ -0,0 +1,12 @@
package com.ubtrobot.jimu.bluetooth.base;
/* loaded from: classes2.dex */
public interface IPacket extends Cloneable {
byte f();
byte[] g();
int getId();
boolean isValid();
}

View File

@@ -0,0 +1,13 @@
package com.ubtrobot.jimu.bluetooth.base;
/* compiled from: ProtocolPacket.java */
/* loaded from: classes2.dex */
enum PROTOCOL_STATE {
HEADER1,
HEADER2,
LENGHT,
CMD,
PARAM,
CHECKSUM,
END
}

View File

@@ -0,0 +1,253 @@
package com.ubtrobot.jimu.bluetooth.base;
import android.util.Log;
import com.ijm.dataencryption.de.DataDecryptTool;
import java.nio.ByteBuffer;
/* loaded from: classes2.dex */
public class ProtocolPacket implements IPacket {
private byte[] a;
private int b;
private byte c;
private byte[] d;
private int e;
private PROTOCOL_STATE f = PROTOCOL_STATE.HEADER1;
private ByteBuffer g = ByteBuffer.allocate(DataDecryptTool.DECRYPT_SP_FILE);
/* renamed from: com.ubtrobot.jimu.bluetooth.base.ProtocolPacket$1, reason: invalid class name */
static /* synthetic */ class AnonymousClass1 {
static final /* synthetic */ int[] a = new int[PROTOCOL_STATE.values().length];
static {
try {
a[PROTOCOL_STATE.HEADER1.ordinal()] = 1;
} catch (NoSuchFieldError unused) {
}
try {
a[PROTOCOL_STATE.HEADER2.ordinal()] = 2;
} catch (NoSuchFieldError unused2) {
}
try {
a[PROTOCOL_STATE.LENGHT.ordinal()] = 3;
} catch (NoSuchFieldError unused3) {
}
try {
a[PROTOCOL_STATE.CMD.ordinal()] = 4;
} catch (NoSuchFieldError unused4) {
}
try {
a[PROTOCOL_STATE.PARAM.ordinal()] = 5;
} catch (NoSuchFieldError unused5) {
}
try {
a[PROTOCOL_STATE.CHECKSUM.ordinal()] = 6;
} catch (NoSuchFieldError unused6) {
}
try {
a[PROTOCOL_STATE.END.ordinal()] = 7;
} catch (NoSuchFieldError unused7) {
}
}
}
public ProtocolPacket() {
this.g.clear();
}
public byte a(byte[] bArr, int i, int i2) {
byte b = 0;
while (i <= i2) {
b = (byte) (b + bArr[i]);
i++;
}
return b;
}
public void a(String str) {
}
public void b(byte[] bArr) {
this.a = new byte[2];
System.arraycopy(bArr, 0, this.a, 0, 2);
this.b = bArr[2] & 255;
this.c = bArr[3];
int i = this.b;
int i2 = 4;
if (i - 5 > 0) {
this.d = new byte[i - 5];
System.arraycopy(bArr, 4, this.d, 0, i - 5);
int i3 = this.b;
i2 = 4 + (i3 - 5);
this.e = i3 - 5;
}
byte b = bArr[i2];
byte b2 = bArr[i2 + 1];
}
public Object clone() {
try {
return (ProtocolPacket) super.clone();
} catch (CloneNotSupportedException e) {
Log.e("ContentValues", "Clone BleProtocolPacket fail!", e);
return null;
}
}
@Override // com.ubtrobot.jimu.bluetooth.base.IPacket
public byte f() {
return this.c;
}
@Override // com.ubtrobot.jimu.bluetooth.base.IPacket
public byte[] g() {
return this.d;
}
@Override // com.ubtrobot.jimu.bluetooth.base.IPacket
public int getId() {
return this.c;
}
@Override // com.ubtrobot.jimu.bluetooth.base.IPacket
public boolean isValid() {
return true;
}
public void a(byte b) {
this.c = b;
}
public void a(byte[] bArr) {
this.d = bArr;
if (bArr == null) {
this.e = 0;
} else {
this.e = bArr.length;
}
}
public ProtocolPacket(int i, byte[] bArr) {
this.g.clear();
a((byte) i);
a(bArr);
}
public int a() {
return this.e;
}
public void a(int i) {
this.e = i;
}
/* JADX WARN: Can't fix incorrect switch cases order, some code will duplicate */
public boolean b(byte b) {
try {
int i = 0;
switch (AnonymousClass1.a[this.f.ordinal()]) {
case 1:
if (b != -5) {
Log.v("error_blue", "1");
} else {
this.g.clear();
this.g.put(b);
this.f = PROTOCOL_STATE.HEADER2;
}
return false;
case 2:
if (b != -65) {
this.f = PROTOCOL_STATE.HEADER1;
Log.v("error_blue", "2");
if (b == -5) {
b(b);
}
} else {
this.g.put(b);
this.f = PROTOCOL_STATE.LENGHT;
}
return false;
case 3:
this.b = b & 255;
this.g.put(b);
this.f = PROTOCOL_STATE.CMD;
return false;
case 4:
this.c = b;
this.g.put(b);
this.f = PROTOCOL_STATE.PARAM;
this.e = this.b - 5;
this.d = new byte[this.e];
return false;
case 5:
this.g.put(b);
this.e--;
if (this.e == 0) {
this.f = PROTOCOL_STATE.CHECKSUM;
}
return false;
case 6:
if (a(this.g.array(), 2, this.g.position() - 1) != b) {
this.f = PROTOCOL_STATE.HEADER1;
Log.v("error_blue", "3");
if (b == -5) {
b(b);
}
} else {
this.g.put(b);
this.f = PROTOCOL_STATE.END;
}
return false;
case 7:
if (b != -19) {
this.f = PROTOCOL_STATE.HEADER1;
Log.v("error_blue", "4");
if (b == -5) {
b(b);
}
return false;
}
this.g.put(b);
this.f = PROTOCOL_STATE.HEADER1;
int i2 = 0;
while (i < this.b - 5) {
this.d[i2] = this.g.get(i + 4);
i++;
i2++;
}
return true;
default:
return false;
}
} catch (Exception e) {
e.getMessage();
return true;
}
}
public byte[] b() {
int i;
int i2 = this.e;
int i3 = (short) (i2 == 0 ? 7 : i2 + 6);
byte[] bArr = new byte[i3];
int i4 = 0;
bArr[0] = -5;
bArr[1] = -65;
bArr[2] = (byte) ((i3 - 1) & 255);
bArr[3] = this.c;
if (this.e == 0) {
i = 5;
bArr[4] = 0;
} else {
i = 4;
while (i4 < this.e) {
bArr[i] = this.d[i4];
i4++;
i++;
}
}
int i5 = i + 1;
bArr[i] = a(bArr, 2, i5);
bArr[i5] = -19;
return bArr;
}
}

View File

@@ -0,0 +1,164 @@
package com.ubtrobot.jimu.bluetooth.base.discover;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import com.ubtrobot.jimu.bluetooth.Cancellable;
import com.ubtrobot.log.ALog;
import java.util.ArrayList;
import java.util.List;
/* loaded from: classes2.dex */
public class BleDeviceScanner {
private BluetoothAdapter b;
private Handler d;
private ScannedHubEmitter e;
private int a = 5000;
private List<BluetoothDevice> c = new ArrayList();
private BluetoothAdapter.LeScanCallback f = new BluetoothAdapter.LeScanCallback() { // from class: com.ubtrobot.jimu.bluetooth.base.discover.BleDeviceScanner.1
@Override // android.bluetooth.BluetoothAdapter.LeScanCallback
public void onLeScan(BluetoothDevice bluetoothDevice, int i, byte[] bArr) {
if (BleDeviceScanner.this.c.contains(bluetoothDevice)) {
return;
}
BleDeviceScanner.this.c.add(bluetoothDevice);
BleDeviceScanner.this.e.a(new ScanResult(bluetoothDevice, i));
}
};
private ScanCallback g = new ScanCallback() { // from class: com.ubtrobot.jimu.bluetooth.base.discover.BleDeviceScanner.2
@Override // android.bluetooth.le.ScanCallback
public void onBatchScanResults(List<android.bluetooth.le.ScanResult> list) {
super.onBatchScanResults(list);
}
@Override // android.bluetooth.le.ScanCallback
public void onScanFailed(int i) {
Log.e("ContentValues", "Scan ble fail! errorCode:" + i);
super.onScanFailed(i);
BleDeviceScanner.this.e.a(i, "Scan ble device fail! Detail define refer to ScanCallback.SCAN_FAILED_*");
}
@Override // android.bluetooth.le.ScanCallback
@TargetApi(21)
public void onScanResult(int i, android.bluetooth.le.ScanResult scanResult) {
BluetoothDevice device = scanResult.getDevice();
if (BleDeviceScanner.this.c.contains(device)) {
return;
}
BleDeviceScanner.this.c.add(device);
BleDeviceScanner.this.e.a(new ScanResult(device, scanResult.getRssi()));
}
};
private class DiscoverCancelable implements Cancellable, Runnable {
private final Handler a;
private final ScannedHubEmitter b;
private boolean c;
private boolean d;
public DiscoverCancelable(Handler handler, ScannedHubEmitter scannedHubEmitter, int i) {
this.a = handler;
this.a.postDelayed(this, i);
this.b = scannedHubEmitter;
}
@Override // com.ubtrobot.jimu.bluetooth.Cancellable
public synchronized boolean cancel() {
if (!this.d && !this.c) {
this.a.removeCallbacks(this);
BleDeviceScanner.this.b();
this.d = true;
return true;
}
return false;
}
@Override // com.ubtrobot.jimu.bluetooth.Cancellable
public synchronized boolean isCancelled() {
return this.d;
}
@Override // java.lang.Runnable
public synchronized void run() {
if (!this.d) {
this.c = true;
BleDeviceScanner.this.b();
this.b.a();
}
}
}
public BleDeviceScanner(Context context) {
this.d = new Handler(context.getMainLooper());
this.b = ((BluetoothManager) context.getSystemService("bluetooth")).getAdapter();
}
/* JADX INFO: Access modifiers changed from: private */
public void b() {
BluetoothAdapter bluetoothAdapter = this.b;
if (bluetoothAdapter == null) {
return;
}
if (Build.VERSION.SDK_INT < 21) {
bluetoothAdapter.stopLeScan(this.f);
return;
}
BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
if (bluetoothLeScanner == null) {
return;
}
bluetoothLeScanner.stopScan(this.g);
ALog.a("ContentValues").d("call BluetoothLeScanner.stopScan by new api after Android LOLLIPOP");
}
public Cancellable a(ScannedHubEmitter scannedHubEmitter, int i) {
BluetoothAdapter bluetoothAdapter = this.b;
if (bluetoothAdapter == null) {
Log.e("ContentValues", "Bluetooth is not support!");
this.e.a(4, "Scan fail as bluetooth is not support");
return null;
}
if (bluetoothAdapter.getState() != 12) {
scannedHubEmitter.a(-3, "Bluetooth is not turn on!");
return null;
}
if (i < 5000) {
Log.e("ContentValues", "Duration must greater than 5000");
this.a = 5000;
} else {
this.a = i;
}
DiscoverCancelable discoverCancelable = new DiscoverCancelable(this.d, scannedHubEmitter, this.a);
this.e = scannedHubEmitter;
try {
a();
} catch (Exception e) {
Log.e("ContentValues", "Start scan fail", e);
}
return discoverCancelable;
}
private void a() {
if (this.b == null) {
return;
}
this.c.clear();
if (Build.VERSION.SDK_INT >= 21) {
BluetoothLeScanner bluetoothLeScanner = this.b.getBluetoothLeScanner();
if (bluetoothLeScanner == null) {
return;
}
bluetoothLeScanner.startScan(this.g);
ALog.a("ContentValues").d("call BluetoothLeScanner.startScan by new api after Android LOLLIPOP");
return;
}
this.b.startLeScan(this.f);
}
}

View File

@@ -0,0 +1,22 @@
package com.ubtrobot.jimu.bluetooth.base.discover;
import android.bluetooth.BluetoothDevice;
/* loaded from: classes2.dex */
public class ScanResult {
private BluetoothDevice a;
private int b;
public ScanResult(BluetoothDevice bluetoothDevice, int i) {
this.a = bluetoothDevice;
this.b = i;
}
public BluetoothDevice a() {
return this.a;
}
public int b() {
return this.b;
}
}

View File

@@ -0,0 +1,10 @@
package com.ubtrobot.jimu.bluetooth.base.discover;
/* loaded from: classes2.dex */
public interface ScannedHubEmitter {
void a();
void a(int i, String str);
void a(ScanResult scanResult);
}

View File

@@ -0,0 +1,13 @@
package com.ubtrobot.jimu.bluetooth.ble;
/* compiled from: BleDeviceProcessThread.java */
/* loaded from: classes2.dex */
class BUFFER_DATA {
public byte[] a;
public int b;
public long c;
public int d;
BUFFER_DATA() {
}
}

View File

@@ -0,0 +1,197 @@
package com.ubtrobot.jimu.bluetooth.ble;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.os.SystemClock;
import android.util.Log;
import com.afunx.ble.blelitelib.log.BleLiteLog;
import com.afunx.ble.blelitelib.proxy.BleGattClientProxy;
import com.afunx.ble.blelitelib.utils.BleUuidUtils;
import com.ubtrobot.jimu.bluetooth.base.ProtocolPacket;
import com.ubtrobot.jimu.bluetooth.ble.BleDeviceProcessThread;
import com.ubtrobot.jimu.bluetooth.utils.ByteHexHelper;
/* loaded from: classes2.dex */
public class BleClientHandler extends Thread implements BleDeviceProcessThread.Callback {
private static final String p = BleClientHandler.class.getSimpleName();
private String a;
private BleGattClientProxy b;
private BluetoothGattService c;
private BluetoothGattCharacteristic d;
private BluetoothGattCharacteristic e;
private int l;
private int m;
private ClientCallback n;
private boolean h = true;
private boolean k = true;
private BleGattClientProxy.OnCharacteristicNotificationListener o = new BleGattClientProxy.OnCharacteristicNotificationListener() { // from class: com.ubtrobot.jimu.bluetooth.ble.BleClientHandler.1
@Override // com.afunx.ble.blelitelib.proxy.BleGattClientProxy.OnCharacteristicNotificationListener
public synchronized void onCharacteristicNotification(byte[] bArr) {
if (bArr != null) {
if (bArr.length != 0) {
try {
Log.i(BleClientHandler.p, "onReceive:msg :" + ByteHexHelper.a(bArr));
for (byte b : bArr) {
if (BleClientHandler.this.f.b(b)) {
if (BleClientHandler.this.n != null) {
BleClientHandler.this.f.a(BleClientHandler.this.f.g().length);
BleClientHandler.this.n.a(BleClientHandler.this.a, BleClientHandler.this.f.f(), BleClientHandler.this.f.g(), BleClientHandler.this.f.a());
}
BleClientHandler.this.l = 0;
BleClientHandler.this.m = 0;
BleClientHandler.this.i = SystemClock.uptimeMillis();
BleClientHandler.this.g.a(BleClientHandler.this.f.f());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
};
private ProtocolPacket f = new ProtocolPacket();
private long i = SystemClock.uptimeMillis();
private long j = this.i;
private BleDeviceProcessThread g = new BleDeviceProcessThread(this);
public interface ClientCallback {
void a(String str);
void a(String str, byte b, byte[] bArr, int i);
}
public BleClientHandler(String str, BleGattClientProxy bleGattClientProxy, ClientCallback clientCallback) {
this.l = 0;
this.m = 0;
this.a = str;
this.b = bleGattClientProxy;
this.n = clientCallback;
this.l = 0;
this.m = 0;
this.g.start();
b();
}
@Override // java.lang.Thread, java.lang.Runnable
public void run() {
while (this.h) {
try {
if (this.c == null) {
this.c = this.b.discoverService(BleUuidUtils.str2uuid("49535343-fe7d-4ae5-8fa9-9fafd205e455"), 5000L);
}
if (this.d == null) {
this.d = this.b.discoverCharacteristic(this.c, BleUuidUtils.str2uuid("49535343-1e4d-4bd9-ba61-23c647249616"));
}
if (this.e == null) {
this.e = this.b.discoverCharacteristic(this.c, BleUuidUtils.str2uuid("49535343-8841-43f4-a8d4-ecbe34729bb3"));
}
} catch (Exception unused) {
this.h = false;
return;
}
}
}
public void c(byte[] bArr, int i) {
if (SystemClock.uptimeMillis() - this.j < 3000) {
return;
}
if (!this.k) {
this.i = SystemClock.uptimeMillis();
} else {
a(bArr, i);
this.l++;
}
}
public boolean d() {
return (this.h && isAlive() && (!(this.l > 3 || this.m > 6) || !this.k)) ? false : true;
}
public void b(byte[] bArr, int i) {
this.g.a(bArr, i);
}
public String a() {
return this.a;
}
public void b() {
if (this.c == null) {
BleGattClientProxy bleGattClientProxy = this.b;
if (bleGattClientProxy == null) {
return;
} else {
this.c = bleGattClientProxy.discoverService(BleUuidUtils.str2uuid("49535343-fe7d-4ae5-8fa9-9fafd205e455"), 5000L);
}
}
BluetoothGattService bluetoothGattService = this.c;
if (bluetoothGattService == null) {
Log.e(p, "gattWriteService is null");
return;
}
if (this.d == null) {
BleGattClientProxy bleGattClientProxy2 = this.b;
if (bleGattClientProxy2 == null || bluetoothGattService == null) {
return;
} else {
this.d = bleGattClientProxy2.discoverCharacteristic(bluetoothGattService, BleUuidUtils.str2uuid("49535343-1e4d-4bd9-ba61-23c647249616"));
}
}
BleGattClientProxy bleGattClientProxy3 = this.b;
if (bleGattClientProxy3 == null) {
return;
}
BluetoothGattCharacteristic bluetoothGattCharacteristic = this.d;
if (bluetoothGattCharacteristic == null) {
BleLiteLog.e(p, "registerCharacteristicNotification fail! Because gattNotifyCharacteristic is null! ");
} else {
bleGattClientProxy3.registerCharacteristicNotification(bluetoothGattCharacteristic, this.o);
}
}
public void a(boolean z) {
this.k = z;
}
@Override // com.ubtrobot.jimu.bluetooth.ble.BleDeviceProcessThread.Callback
public synchronized void a(byte[] bArr, int i) {
try {
Log.i("Handler-", "onSendData");
if (this.c == null) {
this.c = this.b.discoverService(BleUuidUtils.str2uuid("49535343-fe7d-4ae5-8fa9-9fafd205e455"), 5000L);
}
if (this.e == null) {
this.e = this.b.discoverCharacteristic(this.c, BleUuidUtils.str2uuid("49535343-8841-43f4-a8d4-ecbe34729bb3"));
}
Log.i(p, "onSend:" + ByteHexHelper.a(bArr));
boolean writeCharacterisitcNoResponse2 = this.b.writeCharacterisitcNoResponse2(this.e, bArr);
this.j = SystemClock.uptimeMillis();
this.m = this.m + 1;
Log.i(p, "sendNormalCount: " + this.m + " writeSucc: " + writeCharacterisitcNoResponse2);
} catch (Exception e) {
e.printStackTrace();
c();
}
}
public void c() {
synchronized (this) {
try {
this.l = 0;
this.m = 0;
this.h = false;
if (this.g != null) {
this.g.a();
}
if (this.n != null) {
this.n.a(this.a);
}
this.b.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

View File

@@ -0,0 +1,115 @@
package com.ubtrobot.jimu.bluetooth.ble;
import android.os.SystemClock;
import android.util.Log;
import com.ubtrobot.jimu.bluetooth.base.ProtocolPacket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/* loaded from: classes2.dex */
public class BleDeviceProcessThread extends Thread {
private static final String d = BleDeviceProcessThread.class.getSimpleName();
private List<BUFFER_DATA> a;
private boolean b = true;
private Callback c;
public interface Callback {
void a(byte[] bArr, int i);
}
public BleDeviceProcessThread(Callback callback) {
this.c = callback;
new ProtocolPacket();
this.a = new ArrayList();
}
public void a(byte[] bArr, int i) {
synchronized (this) {
Log.i(d, "sendData");
BUFFER_DATA buffer_data = new BUFFER_DATA();
buffer_data.a = bArr;
buffer_data.b = i;
buffer_data.c = SystemClock.uptimeMillis();
buffer_data.d = 0;
this.a.add(buffer_data);
if (this.c != null) {
this.c.a(bArr, i);
}
}
}
public void b(byte[] bArr, int i) {
synchronized (this) {
if (this.c != null) {
this.c.a(bArr, i);
}
}
}
@Override // java.lang.Thread, java.lang.Runnable
public void run() {
while (this.b) {
synchronized (this) {
BUFFER_DATA buffer_data = null;
Iterator<BUFFER_DATA> it = this.a.iterator();
while (true) {
if (!it.hasNext()) {
break;
}
BUFFER_DATA next = it.next();
if (SystemClock.uptimeMillis() - next.c >= 10000) {
if (next.d >= 2) {
buffer_data = next;
break;
} else {
b(next.a, next.b);
next.c = SystemClock.uptimeMillis();
next.d++;
}
}
}
if (buffer_data != null) {
this.a.remove(buffer_data);
} else {
try {
Thread.sleep(100L);
} catch (InterruptedException unused) {
this.b = false;
Thread.currentThread().interrupt();
return;
}
}
}
}
}
public void a() {
synchronized (this) {
this.b = false;
this.a.clear();
}
}
public void a(byte b) {
synchronized (this) {
ProtocolPacket protocolPacket = new ProtocolPacket();
BUFFER_DATA buffer_data = null;
Iterator<BUFFER_DATA> it = this.a.iterator();
while (true) {
if (!it.hasNext()) {
break;
}
BUFFER_DATA next = it.next();
protocolPacket.b(next.a);
if (protocolPacket.f() == b) {
buffer_data = next;
break;
}
}
if (buffer_data != null) {
this.a.remove(buffer_data);
}
}
}
}

View File

@@ -0,0 +1,199 @@
package com.ubtrobot.jimu.bluetooth.ble;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import com.ubtrobot.jimu.bluetooth.Cancellable;
import com.ubtrobot.jimu.bluetooth.base.discover.BleDeviceScanner;
import com.ubtrobot.jimu.bluetooth.base.discover.ScannedHubEmitter;
import com.ubtrobot.jimu.bluetooth.proxy.Callback;
import com.ubtrobot.jimu.bluetooth.proxy.Device;
import com.ubtrobot.jimu.bluetooth.proxy.DeviceListener;
import com.ubtrobot.jimu.bluetooth.proxy.Proxy;
import com.ubtrobot.jimu.bluetooth.utils.ByteHexHelper;
import java.util.ArrayList;
import java.util.List;
/* loaded from: classes2.dex */
public class BleLib extends Callback implements Proxy {
private static BleLib e;
private static BleManager f;
private ArrayList<String> b = new ArrayList<>();
private DeviceListener c;
private BleDeviceScanner d;
private BleLib() {
new ArrayList();
new Handler(Looper.getMainLooper());
new BluetoothAdapter.LeScanCallback() { // from class: com.ubtrobot.jimu.bluetooth.ble.BleLib.2
@Override // android.bluetooth.BluetoothAdapter.LeScanCallback
public void onLeScan(BluetoothDevice bluetoothDevice, int i, byte[] bArr) {
String replace = TextUtils.isEmpty(bluetoothDevice.getName()) ? "" : bluetoothDevice.getName().replace("\n", "").replace("\\n", "");
String str = replace + "\n" + bluetoothDevice.getAddress() + "\n" + i;
Log.i("BleLib", str);
if (BleLib.this.c(str)) {
return;
}
BleLib.this.b.add(str);
BleLib.this.c.b(str);
Proxy.a.add(new Device(bluetoothDevice.getAddress(), replace));
}
};
new ScanCallback() { // from class: com.ubtrobot.jimu.bluetooth.ble.BleLib.4
@Override // android.bluetooth.le.ScanCallback
public void onBatchScanResults(List<ScanResult> list) {
super.onBatchScanResults(list);
}
@Override // android.bluetooth.le.ScanCallback
public void onScanFailed(int i) {
Log.e("BleLib", "Scan ble fail! errorCode:" + i);
super.onScanFailed(i);
}
@Override // android.bluetooth.le.ScanCallback
@TargetApi(21)
public void onScanResult(int i, ScanResult scanResult) {
Log.d("BleLib", "onScanResult " + scanResult.getDevice().getName());
BluetoothDevice device = scanResult.getDevice();
String replace = TextUtils.isEmpty(device.getName()) ? "" : device.getName().replace("\n", "").replace("\\n", "");
String str = replace + "\n" + device.getAddress() + "\n" + scanResult.getRssi();
Log.i("BleLib", str);
if (BleLib.this.c(str)) {
return;
}
BleLib.this.b.add(str);
BleLib.this.c.b(str);
Proxy.a.add(new Device(device.getAddress(), replace));
}
};
}
/* JADX INFO: Access modifiers changed from: private */
public boolean c(String str) {
for (int i = 0; i < this.b.size(); i++) {
if (this.b.get(i).equals(str)) {
return true;
}
}
return false;
}
public static synchronized BleLib b() {
BleLib bleLib;
synchronized (BleLib.class) {
if (e == null) {
synchronized (BleLib.class) {
if (e == null) {
e = new BleLib();
}
}
}
bleLib = e;
}
return bleLib;
}
@Override // com.ubtrobot.jimu.bluetooth.proxy.Proxy
public boolean a(Context context, DeviceListener deviceListener) {
this.c = deviceListener;
if (f == null) {
f = new BleManager(context, this);
f.b();
}
if (this.d == null) {
this.d = new BleDeviceScanner(context);
}
return BluetoothAdapter.getDefaultAdapter() != null;
}
@Override // com.ubtrobot.jimu.bluetooth.proxy.Callback
public void b(String str, byte b, byte[] bArr, int i) {
DeviceListener deviceListener = this.c;
if (deviceListener != null) {
deviceListener.a(str, b, bArr, i);
}
}
@Override // com.ubtrobot.jimu.bluetooth.proxy.Callback
public void b(String str) {
DeviceListener deviceListener = this.c;
if (deviceListener != null) {
deviceListener.disconnect(str);
}
}
public Cancellable a(final ScannedHubEmitter scannedHubEmitter, int i) {
return this.d.a(new ScannedHubEmitter() { // from class: com.ubtrobot.jimu.bluetooth.ble.BleLib.1
@Override // com.ubtrobot.jimu.bluetooth.base.discover.ScannedHubEmitter
public void a(com.ubtrobot.jimu.bluetooth.base.discover.ScanResult scanResult) {
if (scanResult.a() == null || scanResult.a().getName() == null || !scanResult.a().getName().toLowerCase().contains("jimu")) {
return;
}
scannedHubEmitter.a(scanResult);
BluetoothDevice a = scanResult.a();
int b = scanResult.b();
String replace = TextUtils.isEmpty(a.getName()) ? "" : a.getName().replace("\n", "").replace("\\n", "");
String str = replace + "\n" + a.getAddress() + "\n" + b;
Log.v("BleLib", str);
if (BleLib.this.c(str)) {
return;
}
BleLib.this.b.add(str);
BleLib.this.c.b(str);
Proxy.a.add(new Device(a.getAddress(), replace));
}
@Override // com.ubtrobot.jimu.bluetooth.base.discover.ScannedHubEmitter
public void a(int i2, String str) {
scannedHubEmitter.a(i2, str);
}
@Override // com.ubtrobot.jimu.bluetooth.base.discover.ScannedHubEmitter
public void a() {
scannedHubEmitter.a();
}
}, i);
}
@Override // com.ubtrobot.jimu.bluetooth.proxy.Proxy
public void a(String str) {
if (TextUtils.isEmpty(str)) {
return;
}
Log.i("BleLib", "connect: mac: " + str);
f.d(str);
}
@Override // com.ubtrobot.jimu.bluetooth.proxy.Proxy
public void a() {
f.a();
}
@Override // com.ubtrobot.jimu.bluetooth.proxy.Proxy
public void a(String str, boolean z) {
f.a(str, z);
}
@Override // com.ubtrobot.jimu.bluetooth.proxy.Proxy
public synchronized void a(String str, byte b, byte[] bArr, int i) {
Log.i("BleLib", "sendData:" + ByteHexHelper.a(bArr) + " cmd:" + ((int) b));
f.b(str, b, bArr, i);
Log.i("BleLib", "after-sendData");
}
@Override // com.ubtrobot.jimu.bluetooth.proxy.Callback
public void a(boolean z, String str) {
DeviceListener deviceListener = this.c;
if (deviceListener != null) {
deviceListener.onConnectState(z, str);
}
}
}

View File

@@ -0,0 +1,174 @@
package com.ubtrobot.jimu.bluetooth.ble;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import com.afunx.ble.blelitelib.proxy.BleGattClientProxy;
import com.afunx.ble.blelitelib.proxy.BleGattClientProxyImpl;
import com.ubtrobot.jimu.bluetooth.base.ProtocolPacket;
import com.ubtrobot.jimu.bluetooth.ble.BleClientHandler;
import com.ubtrobot.jimu.bluetooth.proxy.Callback;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/* loaded from: classes2.dex */
public class BleManager extends Thread implements BleClientHandler.ClientCallback {
private static final String f = BleManager.class.getSimpleName();
private boolean a = true;
private BleGattClientProxy b;
private Callback c;
private List<BleClientHandler> d;
private Handler e;
public BleManager(Context context, Callback callback) {
new ArrayList();
new ArrayList();
this.d = new ArrayList();
this.e = new Handler(Looper.getMainLooper());
this.b = new BleGattClientProxyImpl(context.getApplicationContext());
this.c = callback;
}
public synchronized void d(final String str) {
if (TextUtils.isEmpty(str)) {
return;
}
Log.i(f, "connect: mac: " + str);
new Thread(new Runnable() { // from class: com.ubtrobot.jimu.bluetooth.ble.BleManager.1
@Override // java.lang.Runnable
public void run() {
final boolean connect = BleManager.this.b.connect(str, 30000L);
BleManager.this.b(str);
BleManager.this.e.post(new Runnable() { // from class: com.ubtrobot.jimu.bluetooth.ble.BleManager.1.1
@Override // java.lang.Runnable
public void run() {
BleManager.this.c.a(connect, str);
}
});
}
}).start();
}
@Override // java.lang.Thread, java.lang.Runnable
public void run() {
BleClientHandler bleClientHandler;
while (this.a) {
synchronized (this) {
Iterator<BleClientHandler> it = this.d.iterator();
while (true) {
if (!it.hasNext()) {
bleClientHandler = null;
break;
}
bleClientHandler = it.next();
if (bleClientHandler.d()) {
Log.i(f, "tryToReleaseConnection");
break;
}
ProtocolPacket protocolPacket = new ProtocolPacket();
protocolPacket.a((byte) 3);
protocolPacket.a((byte[]) null);
protocolPacket.a(0);
byte[] b = protocolPacket.b();
bleClientHandler.c(b, b.length);
}
if (bleClientHandler != null) {
String a = bleClientHandler.a();
bleClientHandler.c();
this.d.remove(bleClientHandler);
if (this.c != null) {
this.c.b(a);
}
} else {
try {
Thread.sleep(300L);
} catch (InterruptedException unused) {
this.a = false;
Thread.currentThread().interrupt();
return;
}
}
}
}
}
public synchronized void a() {
if (this.d != null) {
Iterator<BleClientHandler> it = this.d.iterator();
while (it.hasNext()) {
it.next().c();
}
this.d.clear();
}
}
public void b() {
this.a = true;
start();
}
public synchronized BleClientHandler c(String str) {
BleClientHandler bleClientHandler;
bleClientHandler = null;
Iterator<BleClientHandler> it = this.d.iterator();
while (true) {
if (!it.hasNext()) {
break;
}
BleClientHandler next = it.next();
if (next.a().equals(str)) {
bleClientHandler = next;
break;
}
}
return bleClientHandler;
}
public synchronized void b(String str, byte b, byte[] bArr, int i) {
ProtocolPacket protocolPacket = new ProtocolPacket();
protocolPacket.a(b);
protocolPacket.a(bArr);
protocolPacket.a(i);
byte[] b2 = protocolPacket.b();
BleClientHandler c = c(str);
if (c != null) {
c.b(b2, b2.length);
}
}
public void a(String str, boolean z) {
BleClientHandler c = c(str);
if (c != null) {
c.a(z);
}
}
@Override // com.ubtrobot.jimu.bluetooth.ble.BleClientHandler.ClientCallback
public synchronized void a(String str, byte b, byte[] bArr, int i) {
if (this.c != null) {
this.c.b(str, b, bArr, i);
}
}
@Override // com.ubtrobot.jimu.bluetooth.ble.BleClientHandler.ClientCallback
public synchronized void a(String str) {
if (this.c != null) {
this.c.b(str);
}
}
public synchronized void b(String str) {
if (c(str) != null) {
return;
}
if (this.b == null) {
return;
}
BleClientHandler bleClientHandler = new BleClientHandler(str, this.b, this);
this.d.add(bleClientHandler);
bleClientHandler.start();
}
}

View File

@@ -0,0 +1,162 @@
package com.ubtrobot.jimu.bluetooth.proxy;
import android.content.Context;
import android.util.Log;
import com.ubtech.jimu.storage.UbtPrefs;
import com.ubtrobot.jimu.bluetooth.Cancellable;
import com.ubtrobot.jimu.bluetooth.base.BluetoothLib;
import com.ubtrobot.jimu.bluetooth.base.discover.ScanResult;
import com.ubtrobot.jimu.bluetooth.base.discover.ScannedHubEmitter;
import com.ubtrobot.jimu.bluetooth.ble.BleLib;
import com.ubtrobot.log.ALog;
import java.util.ArrayList;
import java.util.Iterator;
/* loaded from: classes2.dex */
public class BluetoothProxy implements Proxy {
private static final String i = "BluetoothProxy";
private static BluetoothProxy j;
private Context c;
private DeviceListener d;
private UbtPrefs e;
private Cancellable g;
private Cancellable h;
private Proxy b = BleLib.b();
private ArrayList<String> f = new ArrayList<>();
private BluetoothProxy() {
this.f.add("lemobile");
this.f.add("meizu");
this.f.add("vivo");
this.f.add("oneplus");
this.f.add("oppo");
this.f.add("lenove");
}
public static synchronized BluetoothProxy c() {
BluetoothProxy bluetoothProxy;
synchronized (BluetoothProxy.class) {
if (j == null) {
j = new BluetoothProxy();
}
bluetoothProxy = j;
}
return bluetoothProxy;
}
@Override // com.ubtrobot.jimu.bluetooth.proxy.Proxy
public boolean a(Context context, DeviceListener deviceListener) {
this.c = context;
this.d = deviceListener;
this.e = new UbtPrefs(context);
Log.i(i, "init ble");
BluetoothLib.d().a(context, deviceListener);
return BleLib.b().a(context, deviceListener);
}
public Cancellable a(final ScannedHubEmitter scannedHubEmitter, final int i2) {
if (this.e.a("sp_key_is_last_connect_ble", (Boolean) true).booleanValue()) {
this.g = BleLib.b().a(new ScannedHubEmitter(this) { // from class: com.ubtrobot.jimu.bluetooth.proxy.BluetoothProxy.1
@Override // com.ubtrobot.jimu.bluetooth.base.discover.ScannedHubEmitter
public void a(ScanResult scanResult) {
scannedHubEmitter.a(scanResult);
}
@Override // com.ubtrobot.jimu.bluetooth.base.discover.ScannedHubEmitter
public void a(int i3, String str) {
scannedHubEmitter.a(i3, str);
}
@Override // com.ubtrobot.jimu.bluetooth.base.discover.ScannedHubEmitter
public void a() {
ALog.a(BluetoothProxy.i).d("Ble scan end, start classical bluetooth scan");
BluetoothLib.d().a(scannedHubEmitter, i2 / 2);
}
}, i2 / 2);
} else {
this.h = BluetoothLib.d().a(new ScannedHubEmitter(this) { // from class: com.ubtrobot.jimu.bluetooth.proxy.BluetoothProxy.2
@Override // com.ubtrobot.jimu.bluetooth.base.discover.ScannedHubEmitter
public void a(ScanResult scanResult) {
scannedHubEmitter.a(scanResult);
}
@Override // com.ubtrobot.jimu.bluetooth.base.discover.ScannedHubEmitter
public void a(int i3, String str) {
scannedHubEmitter.a(i3, str);
}
@Override // com.ubtrobot.jimu.bluetooth.base.discover.ScannedHubEmitter
public void a() {
ALog.a(BluetoothProxy.i).d("Classical Bluetooth scan end, start ble scan");
BleLib.b().a(scannedHubEmitter, i2 / 2);
}
}, i2 / 2);
}
return new Cancellable() { // from class: com.ubtrobot.jimu.bluetooth.proxy.BluetoothProxy.3
@Override // com.ubtrobot.jimu.bluetooth.Cancellable
public boolean cancel() {
if (BluetoothProxy.this.g != null) {
BluetoothProxy.this.g.cancel();
}
if (BluetoothProxy.this.h == null) {
return true;
}
BluetoothProxy.this.h.cancel();
return true;
}
@Override // com.ubtrobot.jimu.bluetooth.Cancellable
public boolean isCancelled() {
return false;
}
};
}
@Override // com.ubtrobot.jimu.bluetooth.proxy.Proxy
public void a(String str) {
boolean z;
Iterator<Device> it = Proxy.a.iterator();
while (true) {
if (!it.hasNext()) {
z = false;
break;
}
Device next = it.next();
String mac = next.getMac();
String name = next.getName();
if (mac.equals(str) && name.startsWith("My_")) {
z = true;
break;
}
}
if (!z) {
Log.i(i, "reinit-classify bluetooth");
this.e.a("sp_key_is_last_connect_ble", (Object) false);
this.b = null;
this.b = BluetoothLib.d();
this.b.a(this.c, this.d);
this.b.a(str);
return;
}
Log.i(i, "reinit-ble");
this.e.a("sp_key_is_last_connect_ble", (Object) true);
this.b = BleLib.b();
this.b.a(this.c, this.d);
this.b.a(str);
}
@Override // com.ubtrobot.jimu.bluetooth.proxy.Proxy
public void a() {
this.b.a();
}
@Override // com.ubtrobot.jimu.bluetooth.proxy.Proxy
public void a(String str, boolean z) {
this.b.a(str, z);
}
@Override // com.ubtrobot.jimu.bluetooth.proxy.Proxy
public void a(String str, byte b, byte[] bArr, int i2) {
this.b.a(str, b, bArr, i2);
}
}

View File

@@ -0,0 +1,10 @@
package com.ubtrobot.jimu.bluetooth.proxy;
/* loaded from: classes2.dex */
public abstract class Callback {
public abstract void a(boolean z, String str);
public abstract void b(String str);
public abstract void b(String str, byte b, byte[] bArr, int i);
}

View File

@@ -0,0 +1,30 @@
package com.ubtrobot.jimu.bluetooth.proxy;
import java.io.Serializable;
/* loaded from: classes2.dex */
public class Device implements Serializable {
private String mac;
private String name;
public Device(String str, String str2) {
this.mac = str;
this.name = str2;
}
public String getMac() {
return this.mac;
}
public String getName() {
return this.name;
}
public void setMac(String str) {
this.mac = str;
}
public void setName(String str) {
this.name = str;
}
}

View File

@@ -0,0 +1,14 @@
package com.ubtrobot.jimu.bluetooth.proxy;
/* loaded from: classes2.dex */
public interface DeviceListener {
/* renamed from: a */
void disconnect(String str);
void a(String str, byte b, byte[] bArr, int i);
/* renamed from: a */
void onConnectState(boolean z, String str);
String b(String str);
}

View File

@@ -0,0 +1,20 @@
package com.ubtrobot.jimu.bluetooth.proxy;
import android.content.Context;
import java.util.ArrayList;
import java.util.List;
/* loaded from: classes2.dex */
public interface Proxy {
public static final List<Device> a = new ArrayList();
void a();
void a(String str);
void a(String str, byte b, byte[] bArr, int i);
void a(String str, boolean z);
boolean a(Context context, DeviceListener deviceListener);
}

View File

@@ -0,0 +1,20 @@
package com.ubtrobot.jimu.bluetooth.utils;
/* loaded from: classes2.dex */
public class ByteHexHelper {
public static String a(byte[] bArr) {
StringBuilder sb = new StringBuilder("");
if (bArr == null || bArr.length <= 0) {
return "";
}
for (byte b : bArr) {
String hexString = Integer.toHexString(b & 255);
if (hexString.length() < 2) {
sb.append(0);
}
sb.append(hexString);
sb.append(" ");
}
return sb.toString();
}
}

View File

@@ -0,0 +1,121 @@
package com.ubtrobot.jimu.bluetooth.view;
import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import com.ubtrobot.jimu.bluetooth.ConnectionState;
import com.ubtrobot.jimu.bluetooth.ConnectionStateListener;
import com.ubtrobot.jimu.bluetooth.JimuBluetoothManager;
import com.ubtrobot.jimu.bluetooth.base.BluetoothLib;
import com.ubtrobot.log.ALog;
import java.util.Timer;
import java.util.TimerTask;
/* loaded from: classes2.dex */
public class BluetoothActivity extends Activity {
private static final String e = BluetoothActivity.class.getSimpleName();
private Timer a = new Timer();
private String b = null;
private ConnectionStateListener c = new ConnectionStateListener() { // from class: com.ubtrobot.jimu.bluetooth.view.BluetoothActivity.2
@Override // com.ubtrobot.jimu.bluetooth.ConnectionStateListener
public void onConnectionStateChange(String str, ConnectionState connectionState) {
ALog.a(BluetoothActivity.e).d(str + "Bluetooth state changed, new ConnectionState:" + connectionState);
if (str == null) {
return;
}
if (connectionState == ConnectionState.STATE_CONNECTED || connectionState == ConnectionState.STATE_DISCONNECTED) {
BluetoothActivity.this.finish();
}
}
};
private final BroadcastReceiver d = new BroadcastReceiver() { // from class: com.ubtrobot.jimu.bluetooth.view.BluetoothActivity.3
@Override // android.content.BroadcastReceiver
public void onReceive(Context context, Intent intent) {
char c;
String action = intent.getAction();
ALog.a(BluetoothActivity.e).d("Receive bluetooth broadcast action: " + action);
int hashCode = action.hashCode();
if (hashCode != -223687943) {
if (hashCode == 2116862345 && action.equals("android.bluetooth.device.action.BOND_STATE_CHANGED")) {
c = 0;
}
c = 65535;
} else {
if (action.equals("android.bluetooth.device.action.PAIRING_REQUEST")) {
c = 1;
}
c = 65535;
}
if (c != 0) {
return;
}
BluetoothDevice bluetoothDevice = (BluetoothDevice) intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
Log.w(BluetoothActivity.e, "蓝牙设备的状态" + bluetoothDevice.getBondState());
switch (bluetoothDevice.getBondState()) {
case 10:
Log.w(BluetoothActivity.e, "取消配对");
BluetoothActivity.this.finish();
break;
case 11:
Log.w(BluetoothActivity.e, "正在配对......");
break;
case 12:
Log.w(BluetoothActivity.e, "完成配对");
BluetoothActivity.this.finish();
break;
}
}
};
@Override // android.app.Activity
public void onCreate(Bundle bundle) {
ALog.a(e).d("===== onCreate ======= ");
super.onCreate(bundle);
String stringExtra = getIntent().getStringExtra("MacAddr");
if (stringExtra != null) {
ALog.a(e).d("Bluetooth connect " + stringExtra);
BluetoothLib.d().a(stringExtra);
this.b = stringExtra;
JimuBluetoothManager.d().a(this.c);
this.a.schedule(new TimerTask() { // from class: com.ubtrobot.jimu.bluetooth.view.BluetoothActivity.1
@Override // java.util.TimerTask, java.lang.Runnable
public void run() {
Log.i(BluetoothActivity.e, "Timeout and finish BluetoothActivity!");
BluetoothActivity.this.finish();
}
}, 15000L);
} else {
finish();
}
IntentFilter intentFilter = new IntentFilter("android.bluetooth.device.action.PAIRING_REQUEST");
intentFilter.addAction("android.bluetooth.device.action.BOND_STATE_CHANGED");
intentFilter.addAction("android.bluetooth.device.action.ACL_CONNECTED");
intentFilter.addAction("android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED");
intentFilter.addAction("android.bluetooth.device.action.ACL_DISCONNECTED");
intentFilter.addAction("android.bluetooth.adapter.action.STATE_CHANGED");
intentFilter.addAction("android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED");
registerReceiver(this.d, intentFilter);
}
@Override // android.app.Activity
public void onDestroy() {
ALog.a(e).d("======= onDestroy ========");
if (this.b != null) {
JimuBluetoothManager.d().b(this.c);
}
unregisterReceiver(this.d);
this.a.cancel();
super.onDestroy();
}
@Override // android.app.Activity
public void onResume() {
ALog.a(e).d("===== onResume ======= ");
super.onResume();
}
}

View File

@@ -0,0 +1,8 @@
package com.ubtrobot.jimu.connection;
import com.ubtrobot.jimu.bluetooth.base.IPacket;
/* loaded from: classes2.dex */
public interface PacketsReceiveListener {
void a(String str, IPacket iPacket);
}

View File

@@ -0,0 +1,24 @@
package com.ubtrobot.jimu.connection;
/* loaded from: classes2.dex */
public class RequestException extends Exception {
public static final int ERR_CODE_BT_NOT_CONNECTED = -1;
public static final int ERR_CODE_CMD_INVALID = -4;
public static final int ERR_CODE_TIMEOUT = -3;
public static final String ERR_MSG_CMD_TIMEOUT = "Send command timeout";
public static final String ERR_MSG_NOT_CONNECT = "Bluetooth not connected";
private final int mCode;
public RequestException(int i, String str) {
this(i, str, null);
}
public int getCode() {
return this.mCode;
}
public RequestException(int i, String str, Throwable th) {
super(str, th);
this.mCode = i;
}
}

View File

@@ -0,0 +1,10 @@
package com.ubtrobot.jimu.connection;
import com.ubtrobot.jimu.bluetooth.base.IPacket;
/* loaded from: classes2.dex */
public interface ResponseCallback {
void a(IPacket iPacket, IPacket iPacket2);
void a(IPacket iPacket, RequestException requestException);
}

View File

@@ -0,0 +1,8 @@
package com.ubtrobot.jimu.connection;
/* loaded from: classes2.dex */
public interface ResultCallback {
void a(int i, String str);
void onSuccess();
}

View File

@@ -0,0 +1,392 @@
package com.ubtrobot.jimu.connection;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import com.ubtrobot.jimu.bluetooth.ConnectCallback;
import com.ubtrobot.jimu.bluetooth.ConnectionState;
import com.ubtrobot.jimu.bluetooth.ConnectionStateListener;
import com.ubtrobot.jimu.bluetooth.DataReceiveListener;
import com.ubtrobot.jimu.bluetooth.JimuBluetoothManager;
import com.ubtrobot.jimu.bluetooth.base.IPacket;
import com.ubtrobot.jimu.bluetooth.base.ProtocolPacket;
import com.ubtrobot.log.ALog;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/* loaded from: classes2.dex */
public class RobotConnection {
private static final String p = "RobotConnection";
private Context a;
private JimuBluetoothManager b;
private Handler d;
private String g;
private IPacket h;
protected Handler l;
private final ArrayDeque<IPacket> e = new ArrayDeque<>();
private ExecutorService f = Executors.newSingleThreadExecutor();
private Object i = new Object();
private DataReceiveListener j = new DataReceiveListener() { // from class: com.ubtrobot.jimu.connection.RobotConnection.1
@Override // com.ubtrobot.jimu.bluetooth.DataReceiveListener
public void onDataAvailable(String str, byte b, byte[] bArr) {
ProtocolPacket protocolPacket = new ProtocolPacket();
protocolPacket.a(b);
protocolPacket.a(bArr);
protocolPacket.a(str);
if (protocolPacket.isValid()) {
RobotConnection.this.a(str, protocolPacket);
} else {
Log.e(RobotConnection.p, "Receive an invalid length byte array.");
}
}
};
protected final HashMap<Integer, WrapperResponseCallback> k = new HashMap<>();
private volatile boolean m = false;
private Runnable n = new Runnable() { // from class: com.ubtrobot.jimu.connection.RobotConnection.4
@Override // java.lang.Runnable
public void run() {
RobotConnection.this.e();
}
};
private List<PacketsReceiveListener> o = new ArrayList();
private HandlerThread c = new HandlerThread("BtSendDataThread");
public class WrapperResponseCallback implements ResponseCallback {
private final IPacket a;
private final ResponseCallback b;
private final Runnable c;
private int d = 1;
private volatile boolean e;
WrapperResponseCallback(ResponseCallback responseCallback, IPacket iPacket, Handler handler) {
this.b = responseCallback;
this.a = iPacket;
RobotConnection.this.d = handler;
this.c = new Runnable(RobotConnection.this) { // from class: com.ubtrobot.jimu.connection.RobotConnection.WrapperResponseCallback.1
@Override // java.lang.Runnable
public void run() {
ALog.a(RobotConnection.p).d("response timeout! packet:" + WrapperResponseCallback.this.a.getId());
WrapperResponseCallback.this.e = true;
RobotConnection.this.m = false;
RobotConnection.this.f.execute(RobotConnection.this.n);
WrapperResponseCallback wrapperResponseCallback = WrapperResponseCallback.this;
wrapperResponseCallback.a(wrapperResponseCallback.a, new RequestException(-3, "Timeout."));
}
};
}
static /* synthetic */ int e(WrapperResponseCallback wrapperResponseCallback) {
int i = wrapperResponseCallback.d;
wrapperResponseCallback.d = i - 1;
return i;
}
public void a(int i) {
if (i < 1) {
i = 1;
}
this.d = i;
}
void a() {
byte f = this.a.f();
RobotConnection.this.d.postDelayed(this.c, f != 8 ? (f == 26 || f == 35 || f == 128) ? 3000L : 2000L : 6000L);
}
@Override // com.ubtrobot.jimu.connection.ResponseCallback
public void a(IPacket iPacket, final IPacket iPacket2) {
RobotConnection.this.d.post(new Runnable() { // from class: com.ubtrobot.jimu.connection.RobotConnection.WrapperResponseCallback.2
@Override // java.lang.Runnable
public void run() {
synchronized (RobotConnection.this.k) {
WrapperResponseCallback.e(WrapperResponseCallback.this);
if (WrapperResponseCallback.this.d <= 0) {
RobotConnection.this.k.remove(Integer.valueOf(WrapperResponseCallback.this.a.getId()));
}
}
WrapperResponseCallback.this.b.a(WrapperResponseCallback.this.a, iPacket2);
RobotConnection.this.d.removeCallbacks(WrapperResponseCallback.this.c);
}
});
}
@Override // com.ubtrobot.jimu.connection.ResponseCallback
public void a(IPacket iPacket, final RequestException requestException) {
RobotConnection.this.d.post(new Runnable() { // from class: com.ubtrobot.jimu.connection.RobotConnection.WrapperResponseCallback.3
@Override // java.lang.Runnable
public void run() {
synchronized (RobotConnection.this.k) {
WrapperResponseCallback.this.d = 0;
RobotConnection.this.k.remove(Integer.valueOf(WrapperResponseCallback.this.a.getId()));
}
WrapperResponseCallback.this.b.a(WrapperResponseCallback.this.a, requestException);
RobotConnection.this.d.removeCallbacks(WrapperResponseCallback.this.c);
}
});
}
}
public RobotConnection(Context context) {
this.c.start();
this.d = new Handler(this.c.getLooper());
this.a = context.getApplicationContext();
this.l = new Handler(context.getMainLooper());
this.b = JimuBluetoothManager.d();
if (!this.b.supportsBluetooth(this.a)) {
Log.e(p, "Initialize Bluetooth fail!");
} else if (((BluetoothManager) this.a.getSystemService("bluetooth")).getAdapter() == null) {
Toast.makeText(this.a, "请检测设备是否支持蓝牙", 0).show();
} else {
this.b.a(this.j);
}
}
/* JADX INFO: Access modifiers changed from: private */
public void e() {
IPacket poll;
if (ConnectionState.STATE_CONNECTED != a(this.g)) {
Log.w(p, "Robot not connect");
return;
}
if (this.m) {
ALog.a(p).d("is Sending, send nothing and return");
return;
}
synchronized (this.e) {
poll = this.e.poll();
}
if (poll == null) {
return;
}
synchronized (this.i) {
this.h = poll;
}
synchronized (this.k) {
WrapperResponseCallback wrapperResponseCallback = this.k.get(Integer.valueOf(poll.getId()));
if (wrapperResponseCallback == null) {
Log.e(p, "No responseCallback");
return;
}
wrapperResponseCallback.a();
this.m = true;
this.b.a(b(), poll.f(), poll.g());
}
}
private void d() {
if (Looper.myLooper() == Looper.getMainLooper()) {
throw new SyncCallOnMainThreadException();
}
}
public String b() {
return this.g;
}
public void b(ConnectionStateListener connectionStateListener) {
this.b.b(connectionStateListener);
}
private void b(IPacket iPacket, ResponseCallback responseCallback, int i) {
if (iPacket != null && iPacket.isValid()) {
if (ConnectionState.STATE_CONNECTED != a(this.g)) {
responseCallback.a(iPacket, new RequestException(-1, "ERR_CODE_BT_NOT_CONNECTED"));
return;
}
WrapperResponseCallback wrapperResponseCallback = new WrapperResponseCallback(responseCallback, iPacket, this.l);
wrapperResponseCallback.a(i);
synchronized (this.k) {
this.k.put(Integer.valueOf(iPacket.getId()), wrapperResponseCallback);
}
b(iPacket);
return;
}
responseCallback.a(iPacket, new RequestException(-4, "ERR_CODE_CMD_INVALID"));
}
public void a(String str, ConnectCallback connectCallback) {
this.g = str;
this.b.connectWithCallback(str, connectCallback);
}
public void a() {
this.b.disconnect();
}
public synchronized ConnectionState a(String str) {
return this.b.getConnectionState(str);
}
public void a(ConnectionStateListener connectionStateListener) {
this.b.a(connectionStateListener);
}
public void a(IPacket iPacket, final ResponseCallback responseCallback, int i) {
d();
final boolean[] zArr = new boolean[1];
final boolean[] zArr2 = new boolean[1];
final ProtocolPacket[] protocolPacketArr = new ProtocolPacket[1];
final RequestException[] requestExceptionArr = new RequestException[1];
b(iPacket, new ResponseCallback(this) { // from class: com.ubtrobot.jimu.connection.RobotConnection.2
@Override // com.ubtrobot.jimu.connection.ResponseCallback
public void a(IPacket iPacket2, IPacket iPacket3) {
synchronized (zArr) {
zArr2[0] = true;
protocolPacketArr[0] = iPacket3;
responseCallback.a(iPacket2, iPacket3);
zArr[0] = true;
ALog.a(RobotConnection.p).d("responded notify");
zArr.notifyAll();
}
}
@Override // com.ubtrobot.jimu.connection.ResponseCallback
public void a(IPacket iPacket2, RequestException requestException) {
synchronized (zArr) {
requestExceptionArr[0] = requestException;
zArr[0] = true;
ALog.a(RobotConnection.p).d("responded notify");
zArr.notifyAll();
}
}
}, i);
synchronized (zArr) {
while (!zArr[0]) {
try {
ALog.a(p).d("responded wait");
zArr.wait();
break;
} catch (InterruptedException e) {
ALog.a(p).c("Interrupted by someone when sync doRequest. req=" + iPacket + "Ignore it.", e);
Thread.currentThread().interrupt();
}
}
if (requestExceptionArr[0] != null) {
responseCallback.a(iPacket, requestExceptionArr[0]);
}
}
}
private void b(IPacket iPacket) {
synchronized (this.e) {
this.e.add(iPacket);
}
this.f.execute(this.n);
}
public void b(PacketsReceiveListener packetsReceiveListener) {
this.o.remove(packetsReceiveListener);
}
public IPacket a(IPacket iPacket) throws RequestException {
ProtocolPacket protocolPacket;
d();
final boolean[] zArr = new boolean[1];
final boolean[] zArr2 = new boolean[1];
final ProtocolPacket[] protocolPacketArr = new ProtocolPacket[1];
final RequestException[] requestExceptionArr = new RequestException[1];
a(iPacket, new ResponseCallback(this) { // from class: com.ubtrobot.jimu.connection.RobotConnection.3
@Override // com.ubtrobot.jimu.connection.ResponseCallback
public void a(IPacket iPacket2, IPacket iPacket3) {
synchronized (zArr) {
zArr2[0] = true;
protocolPacketArr[0] = iPacket3;
zArr[0] = true;
ALog.a(RobotConnection.p).d("responded notify");
zArr.notifyAll();
}
}
@Override // com.ubtrobot.jimu.connection.ResponseCallback
public void a(IPacket iPacket2, RequestException requestException) {
synchronized (zArr) {
requestExceptionArr[0] = requestException;
zArr[0] = true;
ALog.a(RobotConnection.p).d("responded notify");
zArr.notifyAll();
}
}
});
synchronized (zArr) {
while (!zArr[0]) {
try {
ALog.a(p).d("responded wait");
zArr.wait();
break;
} catch (InterruptedException e) {
ALog.a(p).c("Interrupted by someone when sync doRequest. req=" + iPacket + "Ignore it.", e);
Thread.currentThread().interrupt();
}
}
if (requestExceptionArr[0] == null) {
protocolPacket = protocolPacketArr[0];
} else {
throw requestExceptionArr[0];
}
}
return protocolPacket;
}
private void a(IPacket iPacket, ResponseCallback responseCallback) {
b(iPacket, responseCallback, 1);
}
/* JADX INFO: Access modifiers changed from: private */
public void a(String str, ProtocolPacket protocolPacket) {
if (protocolPacket.isValid()) {
if (protocolPacket.f() == 3) {
return;
}
if (protocolPacket.getId() == this.h.getId()) {
this.m = false;
this.f.execute(this.n);
synchronized (this.i) {
if (protocolPacket.getId() != this.h.getId()) {
Log.w(p, "Error response! cmd:" + protocolPacket + " res:" + protocolPacket);
} else {
ProtocolPacket protocolPacket2 = (ProtocolPacket) protocolPacket.clone();
synchronized (this.k) {
WrapperResponseCallback wrapperResponseCallback = this.k.get(Integer.valueOf(protocolPacket.getId()));
if (wrapperResponseCallback == null) {
Log.e(p, "No responseCallback");
} else {
wrapperResponseCallback.a(this.h, protocolPacket2);
}
}
}
}
}
Iterator<PacketsReceiveListener> it = this.o.iterator();
while (it.hasNext()) {
it.next().a(str, protocolPacket);
}
return;
}
Log.i(p, "Receive an packet of not response. packet:" + protocolPacket);
}
public void a(PacketsReceiveListener packetsReceiveListener) {
if (this.o.contains(packetsReceiveListener)) {
return;
}
this.o.add(packetsReceiveListener);
}
public void a(boolean z) {
String str = this.g;
if (str == null) {
Log.e(p, "enableHeartbeat fail, connected device is null");
} else {
this.b.a(str, z);
}
}
}

View File

@@ -0,0 +1,8 @@
package com.ubtrobot.jimu.connection;
/* loaded from: classes2.dex */
public class SyncCallOnMainThreadException extends RuntimeException {
public SyncCallOnMainThreadException() {
super("Sync call on main thread is forbidden.");
}
}

View File

@@ -0,0 +1,31 @@
package com.ubtrobot.jimu.exception;
import android.content.Context;
import com.ubtrobot.jimu.robotapi.R$string;
/* loaded from: classes2.dex */
public class BatteryException extends RobotActiveException {
public static final int CODE_VOLTAGE_HIGH = 1;
public static final int CODE_VOLTAGE_LOW = 0;
private int power;
public BatteryException(int i, int i2, String str) {
super(i, str);
this.power = i2;
}
public String getErrorMessage(Context context) {
int i = this.power;
if (i == 0) {
return context.getResources().getString(R$string.batter_low);
}
if (i == 1) {
return context.getResources().getString(R$string.batter_high);
}
return null;
}
public int getPowerCode() {
return this.power;
}
}

View File

@@ -0,0 +1,121 @@
package com.ubtrobot.jimu.exception;
import android.content.Context;
import com.ubtrobot.jimu.robotapi.R$string;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
/* loaded from: classes2.dex */
public class EngineProtectException extends RobotActiveException {
public static final int CODE_ELECTRICITY = 2;
public static final int CODE_FUSE_ENCRYPT = 64;
public static final int CODE_LOCK = 1;
public static final int CODE_OTHERS = 32;
public static final int CODE_OVER_VOLTAGE = 8;
public static final int CODE_TEMPERATURE = 4;
public static final int CODE_UNDER_VOLTAGE = 16;
private int engineType;
private Map<Integer, List<Integer>> errorMap;
public EngineProtectException(int i, String str, int i2, Map<Integer, List<Integer>> map) {
super(i, str);
this.engineType = i2;
this.errorMap = map;
}
private String getIdString(List<Integer> list) {
if (list == null || list.size() <= 0) {
return "";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
sb.append(list.get(i));
if (i < list.size() - 1) {
sb.append(",");
}
}
return sb.toString();
}
public boolean canUnlock() {
return (getHigherExceptionCode() & 1) > 0;
}
public int getEngineType() {
return this.engineType;
}
public Map<Integer, List<Integer>> getErrorMap() {
return this.errorMap;
}
public List<Integer> getErrorMapByCode(int i) {
Map<Integer, List<Integer>> map = this.errorMap;
if (map == null || map.size() <= 0) {
return null;
}
return this.errorMap.get(Integer.valueOf(i));
}
public String getErrorMessage(Context context, int i, List<Integer> list) {
if (list == null || list.size() <= 0) {
return null;
}
String idString = getIdString(list);
int i2 = this.engineType;
if (i2 != 128) {
if (i2 != 10) {
return null;
}
if (i == 1) {
return String.format(context.getResources().getString(R$string.engine_protect_motor_lock), idString);
}
if (i != 32) {
return null;
}
return String.format(context.getResources().getString(R$string.engine_protect_motor_other), idString);
}
if (i == 1) {
return String.format(context.getResources().getString(R$string.engine_protect_lock), idString);
}
if (i != 2) {
if (i == 4) {
return String.format(context.getResources().getString(R$string.engine_protect_temp), idString);
}
if (i != 8 && i != 16) {
if (i == 32) {
return String.format(context.getResources().getString(R$string.engine_protect_other), idString);
}
if (i != 64) {
return null;
}
return String.format(context.getResources().getString(R$string.engine_protect_encrypt), idString);
}
}
return String.format(context.getResources().getString(R$string.engine_protect_electricity), idString);
}
public int getHigherExceptionCode() {
Map<Integer, List<Integer>> map = this.errorMap;
if (map == null || map.size() <= 0) {
return 0;
}
ArrayList arrayList = new ArrayList(this.errorMap.entrySet());
Collections.sort(arrayList, new Comparator() { // from class: com.ubtrobot.jimu.exception.a
@Override // java.util.Comparator
public final int compare(Object obj, Object obj2) {
int compareTo;
compareTo = ((Integer) ((Map.Entry) obj).getKey()).compareTo((Integer) ((Map.Entry) obj2).getKey());
return compareTo;
}
});
return ((Integer) ((Map.Entry) arrayList.get(0)).getKey()).intValue();
}
public boolean needHandUp() {
return getHigherExceptionCode() == 32 || getHigherExceptionCode() == 64;
}
}

View File

@@ -0,0 +1,21 @@
package com.ubtrobot.jimu.exception;
/* loaded from: classes2.dex */
public class EngineVersionException extends RobotActiveException {
private int mEngineType;
private int mInconformityId;
public EngineVersionException(int i, String str, int i2, int i3) {
super(i, str);
this.mInconformityId = i3;
this.mEngineType = i2;
}
public int getEngineType() {
return this.mEngineType;
}
public int getInconformityIds() {
return this.mInconformityId;
}
}

View File

@@ -0,0 +1,15 @@
package com.ubtrobot.jimu.exception;
/* loaded from: classes2.dex */
public class RobotActiveException extends Exception {
private int errorCode;
public RobotActiveException(int i, String str) {
super(str);
this.errorCode = i;
}
public int getErrorCode() {
return this.errorCode;
}
}

View File

@@ -0,0 +1,38 @@
package com.ubtrobot.jimu.robotapi;
/* loaded from: classes2.dex */
public class BatteryInfo {
private float a;
private float b;
private boolean c;
private boolean d;
public BatteryInfo(float f, float f2, boolean z, boolean z2) {
this.c = false;
this.d = false;
this.a = f;
this.b = f2 <= 100.0f ? f2 : 100.0f;
this.d = z;
this.c = z2;
}
public float a() {
return this.b;
}
public float b() {
return this.a;
}
public boolean c() {
return this.c;
}
public boolean d() {
return this.d;
}
public String toString() {
return "Battery voltage:" + this.a + " percentage:" + this.b + "% isPluginCharger:" + this.d + " isChargingCompleted:" + this.c;
}
}

View File

@@ -0,0 +1,20 @@
package com.ubtrobot.jimu.robotapi;
/* loaded from: classes2.dex */
public class BluetoothSpeakerInfo {
private String a;
private String b;
public BluetoothSpeakerInfo(String str, String str2) {
this.a = str;
this.b = str2;
}
public String a() {
return this.b;
}
public String toString() {
return "name:" + this.b + " mac:" + this.a;
}
}

View File

@@ -0,0 +1,276 @@
package com.ubtrobot.jimu.robotapi;
import com.afunx.ble.blelitelib.utils.HexUtils;
import com.ubtech.utils.XLog;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/* loaded from: classes2.dex */
public class BoardInfo {
private String a;
private float c;
private String f;
private byte[] i;
private int b = 0;
private List<Integer> d = new ArrayList();
private List<Integer> e = new ArrayList();
private List<Integer> g = new ArrayList();
private HashMap<Integer, SensorBoardInfo> h = new HashMap<>();
public class SensorBoardInfo {
private List<Integer> a;
private List<Integer> b;
private String c;
private List<Integer> d;
public SensorBoardInfo(BoardInfo boardInfo) {
}
public List<Integer> d() {
return this.d;
}
public List<Integer> b() {
return this.a;
}
public String c() {
return this.c;
}
public List<Integer> a() {
return this.b;
}
}
private boolean a(int i, int i2) {
return ((i >> i2) & 1) > 0;
}
public List<Integer> a() {
return this.e;
}
public float b() {
return this.c;
}
public int c() {
return this.b;
}
public String d() {
return this.a;
}
public int e() {
return (this.a.startsWith("Jimu_p") || this.a.startsWith("JIMU") || !this.a.startsWith("Jimu_b")) ? 112 : 113;
}
public byte[] f() {
return this.i;
}
public Map<Integer, Integer> g() {
List<Integer> b;
HashMap<Integer, SensorBoardInfo> hashMap = this.h;
if (hashMap == null || hashMap.size() <= 0) {
return null;
}
HashMap hashMap2 = new HashMap(this.h.size());
Iterator<Integer> it = this.h.keySet().iterator();
while (it.hasNext()) {
int intValue = it.next().intValue();
SensorBoardInfo sensorBoardInfo = this.h.get(Integer.valueOf(intValue));
if (sensorBoardInfo != null && (b = sensorBoardInfo.b()) != null && b.size() > 0) {
hashMap2.put(Integer.valueOf(intValue), Integer.valueOf(b.size()));
}
}
return hashMap2;
}
public HashMap<Integer, SensorBoardInfo> h() {
return this.h;
}
public List<Integer> i() {
return this.d;
}
public String j() {
return this.f;
}
public List<Integer> k() {
return this.g;
}
public boolean l() {
if (a().size() != 0) {
return true;
}
Iterator<Map.Entry<Integer, SensorBoardInfo>> it = h().entrySet().iterator();
while (it.hasNext()) {
if (it.next().getValue().a().size() != 0) {
return true;
}
}
return false;
}
private List<Integer> b(byte[] bArr) {
ArrayList arrayList = new ArrayList();
int i = (bArr[3] & 255) | ((bArr[0] & 255) << 24) | ((bArr[1] & 255) << 16) | ((bArr[2] & 255) << 8);
for (int i2 = 0; i2 < 32; i2++) {
if (a(i, i2)) {
arrayList.add(Integer.valueOf(i2 + 1));
}
}
return arrayList;
}
public int a(byte[] bArr) {
int i;
this.i = bArr;
int length = bArr.length;
if (length == 1) {
int i2 = bArr[0] & 255;
if (i2 == 1) {
XLog.d("BoardInfo", "Read board info fail!", new Object[0]);
} else if (i2 == 238) {
XLog.d("BoardInfo", "Read board info fail for board is initing", new Object[0]);
}
return -1;
}
if (length < 10) {
XLog.b("BoardInfo", "Invalid param");
return -1;
}
byte[] bArr2 = new byte[10];
System.arraycopy(bArr, 0, bArr2, 0, bArr2.length);
try {
this.a = new String(bArr2, "UTF-8");
} catch (UnsupportedEncodingException unused) {
XLog.b("BoardInfo", "Unsupported encoding board version name");
}
int i3 = length - 10;
if (i3 < 1) {
XLog.b("BoardInfo", "Board info(0x08 cmd response) not any battery info");
return 0;
}
if (a(bArr[10], 7)) {
this.b = 1;
} else {
this.b = 0;
}
this.c = (r6 & Byte.MAX_VALUE) / 10.0f;
int i4 = i3 - 1;
if (i4 < 16) {
XLog.b("BoardInfo", "Board info(0x08 cmd response) not any servo info");
return 0;
}
byte[] bArr3 = new byte[4];
System.arraycopy(bArr, 11, bArr3, 0, bArr3.length);
int length2 = 11 + bArr3.length;
this.d = b(bArr3);
System.arraycopy(bArr, length2, bArr3, 0, bArr3.length);
int length3 = length2 + bArr3.length;
this.e = b(bArr3);
this.f = HexUtils.bytes2HexString(bArr, length3, 4);
int i5 = length3 + 4;
System.arraycopy(bArr, i5, bArr3, 0, bArr3.length);
int length4 = i5 + bArr3.length;
this.g = b(bArr3);
int i6 = i4 - 16;
if (i6 < 1) {
XLog.b("BoardInfo", "Board info(0x08 cmd response) not any Flash size info");
return 0;
}
int i7 = length4 + 1;
byte b = bArr[length4];
int i8 = (i6 - 1) / 7;
for (int i9 = 1; i9 <= i8; i9++) {
int a = a(i9);
SensorBoardInfo sensorBoardInfo = new SensorBoardInfo(this);
sensorBoardInfo.c = "";
int i10 = i7 + 1;
sensorBoardInfo.a = a(bArr[i7]);
int i11 = i10 + 1;
sensorBoardInfo.b = a(bArr[i10]);
if (a == 10) {
sensorBoardInfo.c = HexUtils.bytes2HexString(bArr, i11, 4);
i = i11 + 4;
} else {
int i12 = i11;
int i13 = 0;
while (i13 < 4) {
int i14 = i12 + 1;
String valueOf = String.valueOf((int) bArr[i12]);
if (valueOf.length() == 1) {
valueOf = "0" + valueOf;
}
sensorBoardInfo.c += valueOf;
i13++;
i12 = i14;
}
i = i12;
}
sensorBoardInfo.d = a(bArr[i]);
i7 = i + 1;
this.h.put(Integer.valueOf(a), sensorBoardInfo);
}
return 0;
}
private List<Integer> a(byte b) {
ArrayList arrayList = new ArrayList();
for (int i = 0; i < 8; i++) {
if (a(b, i)) {
arrayList.add(Integer.valueOf(i + 1));
}
}
return arrayList;
}
private int a(int i) {
switch (i) {
case 1:
return 1;
case 2:
return 3;
case 3:
return 2;
case 4:
return 4;
case 5:
return 5;
case 6:
return 6;
case 7:
return 7;
case 8:
return 8;
case 9:
return 12;
case 10:
return 97;
case 11:
return 96;
case 12:
return 11;
case 13:
return 9;
case 14:
return 10;
case 15:
return 14;
default:
XLog.b("BoardInfo", "INVALID SENSOR INDEX");
return -1;
}
}
}

View File

@@ -0,0 +1,160 @@
package com.ubtrobot.jimu.robotapi;
import android.util.Log;
import com.afunx.ble.blelitelib.utils.HexUtils;
import com.ubtech.utils.XLog;
import com.ubtrobot.jimu.bluetooth.base.IPacket;
import com.ubtrobot.jimu.bluetooth.base.ProtocolPacket;
import com.ubtrobot.jimu.connection.RequestException;
import com.ubtrobot.jimu.connection.RobotConnection;
import java.io.UnsupportedEncodingException;
/* loaded from: classes2.dex */
public class DeviceManager {
private RobotConnection a;
public DeviceManager(RobotConnection robotConnection) {
this.a = robotConnection;
}
public void a(boolean z) throws JimuException {
try {
byte[] g = this.a.a(new ProtocolPacket(5, z ? new byte[]{0} : new byte[]{1})).g();
if (g[0] == 0) {
return;
}
throw new JimuException(-21, "read robot battery info fail! ErrCode:" + ((int) g[0]));
} catch (RequestException e) {
throw new JimuException(e.getCode(), e.getMessage());
}
}
public String b() throws JimuException {
ProtocolPacket protocolPacket = new ProtocolPacket(44, new byte[]{0});
try {
byte[] g = this.a.a(protocolPacket).g();
if (g[0] != 0) {
XLog.b("DeviceManager", "read McuId fail!");
throw new JimuException(-21, "read McuId fail!");
}
byte[] bArr = new byte[g.length - 1];
System.arraycopy(g, 1, bArr, 0, bArr.length);
String bytes2HexString = HexUtils.bytes2HexString(bArr);
Log.d("DeviceManager", "McuId:" + bytes2HexString);
return bytes2HexString;
} catch (RequestException e) {
Log.e("DeviceManager", "Call cmd fail! cmd:" + ((int) protocolPacket.f()), e);
throw new JimuException(e.getCode(), e.getMessage());
}
}
public String c() throws JimuException {
ProtocolPacket protocolPacket = new ProtocolPacket(54, new byte[]{0});
try {
byte[] g = this.a.a(protocolPacket).g();
if (g.length <= 1) {
return "";
}
if (g.length == 1 && g[0] != 0) {
XLog.b("DeviceManager", "read device type(cmd:0x36) fail! errResult:" + ((int) g[0]));
throw new JimuException(-21, "read device type(cmd:0x36) fail! errResult:" + ((int) g[0]));
}
byte[] bArr = new byte[g.length - 1];
System.arraycopy(g, 1, bArr, 0, bArr.length);
try {
String str = new String(bArr, "UTF-8");
XLog.a("DeviceManager", "productName:" + str);
return str;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return String.valueOf(bArr);
}
} catch (RequestException e2) {
Log.e("DeviceManager", "Call cmd fail! cmd:" + ((int) protocolPacket.f()), e2);
throw new JimuException(e2.getCode(), e2.getMessage());
}
}
public BatteryInfo d() throws JimuException {
boolean z = true;
ProtocolPacket protocolPacket = new ProtocolPacket(39, new byte[]{0});
try {
byte[] g = this.a.a(protocolPacket).g();
if (g.length != 1) {
boolean z2 = g[0] != 0;
if (g[1] != 1) {
z = false;
}
return new BatteryInfo(g[2], g[3], z2, z);
}
throw new JimuException(-21, "read robot battery info fail! ErrCode:" + ((int) g[0]));
} catch (RequestException e) {
Log.e("DeviceManager", "Call cmd fail! cmd:" + ((int) protocolPacket.f()), e);
throw new JimuException(e.getCode(), e.getMessage());
}
}
public BoardInfo e() throws JimuException {
String str;
try {
byte[] g = this.a.a(new ProtocolPacket(8, new byte[]{0})).g();
if (g.length != 1) {
BoardInfo boardInfo = new BoardInfo();
boardInfo.a(g);
return boardInfo;
}
int i = g[0] & 255;
if (i == 1) {
str = "Read board info fail!";
XLog.d("DeviceManager", "Read board info fail!", new Object[0]);
} else if (i != 238) {
str = "Read board info fail for invalid error code!";
XLog.d("DeviceManager", "Read board info fail for invalid error code!", new Object[0]);
} else {
str = "Read board info fail for board is initing!";
XLog.d("DeviceManager", "Read board info fail for board is initing!", new Object[0]);
}
throw new JimuException(g[0] & 255, str);
} catch (RequestException e) {
Log.e("DeviceManager", "Read board info fail", e);
throw new JimuException(e.getCode(), e.getMessage());
}
}
public String f() throws JimuException {
ProtocolPacket protocolPacket = new ProtocolPacket(43, new byte[]{7});
try {
byte[] g = this.a.a(protocolPacket).g();
if (g[0] != 0) {
XLog.b("DeviceManager", "read SN fail!");
throw new JimuException(-21, "excuse cmd fail!");
}
byte[] bArr = new byte[g.length - 1];
System.arraycopy(g, 1, bArr, 0, bArr.length);
String str = new String(bArr);
Log.d("DeviceManager", "SN:" + str);
return str;
} catch (RequestException e) {
Log.e("DeviceManager", "Call cmd fail! cmd:" + ((int) protocolPacket.f()), e);
throw new JimuException(e.getCode(), e.getMessage());
}
}
public int g() throws RequestException {
try {
IPacket a = this.a.a(new ProtocolPacket(1, new byte[]{0}));
if (a.g().length == 1) {
return a.g()[0] == 0 ? 0 : -1;
}
return -1;
} catch (RequestException e) {
throw e;
}
}
public boolean a() throws JimuException {
String c = c();
Log.d("DeviceManager", "Product type:" + c);
return "".equals(c) || c.startsWith("JIMU") || c.startsWith("Jimu") || c.startsWith("S1JIMU");
}
}

View File

@@ -0,0 +1,129 @@
package com.ubtrobot.jimu.robotapi;
import android.content.Context;
import android.text.TextUtils;
import com.ubtech.utils.XLog;
import com.ubtrobot.jimu.bluetooth.base.IPacket;
import com.ubtrobot.jimu.exception.BatteryException;
import com.ubtrobot.jimu.exception.EngineProtectException;
import com.ubtrobot.jimu.exception.EngineVersionException;
import com.ubtrobot.jimu.exception.RobotActiveException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/* loaded from: classes2.dex */
public class GlobalExceptionUtil {
public interface ExceptionCallback {
void a(String str, RobotActiveException robotActiveException, List<Integer> list);
}
private boolean a(int i, int i2) {
return ((i >> i2) & 1) > 0;
}
public RobotActiveException a(IPacket iPacket, String str) {
byte[] g = iPacket.g();
int i = g[0] & 255;
XLog.a("woo", "errorCode: %d", Integer.valueOf(i));
if (i == 0) {
return null;
}
if (i == 1) {
return new BatteryException(i, g[1] & 255, "Battery Error");
}
if (i == 2) {
Map<Integer, List<Integer>> a = a(g);
if (a == null || a.size() <= 0) {
return null;
}
return new EngineProtectException(i, "Servo is protected", PeripheralType.SERVO, a);
}
if (i == 3) {
return new EngineVersionException(i, "The Servo version is inconformity", PeripheralType.SERVO, g[1] & 255);
}
if (i != 4) {
return i != 5 ? new RobotActiveException(i, "Unknown Exception") : new EngineVersionException(i, "The Motor version is inconformity", 10, g[1] & 255);
}
Map<Integer, List<Integer>> a2 = a(g);
if (a2 == null || a2.size() <= 0) {
return null;
}
return new EngineProtectException(i, "Motor is protected", 10, a2);
}
private Map<Integer, List<Integer>> a(byte[] bArr) {
HashMap hashMap = new HashMap();
List<Integer> a = a(a(bArr, 1));
if (a != null && a.size() > 0) {
hashMap.put(1, a);
}
List<Integer> a2 = a(a(bArr, 5));
if (a2 != null && a2.size() > 0) {
hashMap.put(2, a2);
}
List<Integer> a3 = a(a(bArr, 9));
if (a3 != null && a3.size() > 0) {
hashMap.put(4, a3);
}
List<Integer> a4 = a(a(bArr, 13));
if (a4 != null && a4.size() > 0) {
hashMap.put(8, a4);
}
List<Integer> a5 = a(a(bArr, 17));
if (a5 != null && a5.size() > 0) {
hashMap.put(16, a5);
}
List<Integer> a6 = a(a(bArr, 21));
if (a6 != null && a6.size() > 0) {
hashMap.put(32, a6);
}
List<Integer> a7 = a(a(bArr, 25));
if (a7 != null && a7.size() > 0) {
hashMap.put(64, a7);
}
return hashMap;
}
private List<Integer> a(int i) {
ArrayList arrayList = null;
for (int i2 = 0; i2 < 32; i2++) {
if (a(i, i2)) {
if (arrayList == null) {
arrayList = new ArrayList();
}
arrayList.add(Integer.valueOf(i2 + 1));
}
}
return arrayList;
}
private int a(byte[] bArr, int i) {
return bArr[i + 3] | (bArr[i] << 24) | (bArr[i + 1] << 16) | (bArr[i + 2] << 8);
}
public static void a(Context context, RobotActiveException robotActiveException, ExceptionCallback exceptionCallback) {
int errorCode = robotActiveException.getErrorCode();
if ((errorCode == 2 || errorCode == 4) && (robotActiveException instanceof EngineProtectException)) {
EngineProtectException engineProtectException = (EngineProtectException) robotActiveException;
int higherExceptionCode = engineProtectException.getHigherExceptionCode();
List<Integer> errorMapByCode = engineProtectException.getErrorMapByCode(higherExceptionCode);
String errorMessage = engineProtectException.getErrorMessage(context, higherExceptionCode, errorMapByCode);
if (TextUtils.isEmpty(errorMessage) || exceptionCallback == null) {
return;
}
exceptionCallback.a(errorMessage, engineProtectException, errorMapByCode);
return;
}
if (errorCode == 1 && (robotActiveException instanceof BatteryException)) {
BatteryException batteryException = (BatteryException) robotActiveException;
String errorMessage2 = batteryException.getErrorMessage(context);
if (TextUtils.isEmpty(errorMessage2) || exceptionCallback == null) {
return;
}
exceptionCallback.a(errorMessage2, batteryException, null);
}
}
}

View File

@@ -0,0 +1,183 @@
package com.ubtrobot.jimu.robotapi;
import com.ubtrobot.jimu.bluetooth.ConnectionState;
import com.ubtrobot.jimu.bluetooth.ConnectionStateListener;
import com.ubtrobot.jimu.bluetooth.base.IPacket;
import com.ubtrobot.jimu.connection.PacketsReceiveListener;
import com.ubtrobot.jimu.connection.RobotConnection;
import com.ubtrobot.jimu.exception.RobotActiveException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
/* loaded from: classes2.dex */
public class GlobalManager implements PacketsReceiveListener, ConnectionStateListener {
private Timer a;
private RobotConnection b;
private DeviceManager c;
private Vector<IPowerStateListener> d;
private Vector<IGlobalExceptionListener> e;
private BatteryInfo f;
private volatile boolean g;
public GlobalManager(RobotConnection robotConnection, DeviceManager deviceManager) {
this.b = robotConnection;
this.c = deviceManager;
this.b.a((PacketsReceiveListener) this);
this.b.a((ConnectionStateListener) this);
}
public void c() {
Timer timer = this.a;
if (timer != null) {
try {
timer.cancel();
this.a = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override // com.ubtrobot.jimu.bluetooth.ConnectionStateListener
public void onConnectionStateChange(String str, ConnectionState connectionState) {
Vector<IPowerStateListener> vector;
Object[] array;
if (connectionState == null || (vector = this.d) == null || vector.size() == 0) {
return;
}
synchronized (this) {
array = this.d.toArray();
}
for (int length = array.length - 1; length >= 0; length--) {
((IPowerStateListener) array[length]).onConnectionStateChange(str, connectionState);
}
}
@Override // com.ubtrobot.jimu.connection.PacketsReceiveListener
public void a(String str, IPacket iPacket) {
if (iPacket == null) {
return;
}
int f = iPacket.f() & 255;
if (f == 5) {
b(str, iPacket);
} else {
if (f != 39) {
return;
}
a(iPacket);
}
}
public void b() {
Timer timer = this.a;
if (timer != null) {
try {
timer.cancel();
} catch (Exception e) {
e.printStackTrace();
}
}
this.a = new Timer();
this.a.schedule(new TimerTask() { // from class: com.ubtrobot.jimu.robotapi.GlobalManager.1
@Override // java.util.TimerTask, java.lang.Runnable
public void run() {
try {
if (GlobalManager.this.g) {
return;
}
GlobalManager.this.c.d();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}, 5000L, 30000L);
}
public void a(boolean z) {
this.g = z;
}
public synchronized BatteryInfo a(IPowerStateListener iPowerStateListener) {
if (this.d == null) {
this.d = new Vector<>();
}
if (!this.d.contains(iPowerStateListener)) {
this.d.add(iPowerStateListener);
}
return this.f;
}
public void b(IPowerStateListener iPowerStateListener) {
Vector<IPowerStateListener> vector = this.d;
if (vector != null) {
vector.removeElement(iPowerStateListener);
}
}
public void b(IGlobalExceptionListener iGlobalExceptionListener) {
Vector<IGlobalExceptionListener> vector = this.e;
if (vector != null) {
vector.removeElement(iGlobalExceptionListener);
}
}
private void b(String str, IPacket iPacket) {
Vector<IGlobalExceptionListener> vector;
RobotActiveException a;
Object[] array;
if (iPacket == null || (vector = this.e) == null || vector.size() == 0 || (a = new GlobalExceptionUtil().a(iPacket, str)) == null) {
return;
}
synchronized (this) {
array = this.e.toArray();
}
if (array == null || array.length == 0) {
return;
}
for (int length = array.length - 1; length >= 0; length--) {
((IGlobalExceptionListener) array[length]).onGlobalException(a);
}
}
public synchronized void a(IGlobalExceptionListener iGlobalExceptionListener) {
if (this.e == null) {
this.e = new Vector<>();
}
if (!this.e.contains(iGlobalExceptionListener)) {
this.e.add(iGlobalExceptionListener);
}
}
public BatteryInfo a() {
return this.f;
}
private void a(IPacket iPacket) {
Object[] array;
if (iPacket == null) {
return;
}
byte[] g = iPacket.g();
if (g.length == 1) {
return;
}
BatteryInfo batteryInfo = new BatteryInfo(g[2], g[3], g[0] != 0, g[1] == 1);
BatteryInfo batteryInfo2 = this.f;
if (batteryInfo2 != null && batteryInfo2.c() == batteryInfo.c() && this.f.d() == batteryInfo.d() && this.f.a() == batteryInfo.a() && this.f.b() == batteryInfo.b()) {
return;
}
this.f = batteryInfo;
Vector<IPowerStateListener> vector = this.d;
if (vector == null || vector.size() == 0) {
return;
}
synchronized (this) {
array = this.d.toArray();
}
for (int length = array.length - 1; length >= 0; length--) {
((IPowerStateListener) array[length]).onPowerStateChanged(batteryInfo);
}
}
}

View File

@@ -0,0 +1,8 @@
package com.ubtrobot.jimu.robotapi;
import com.ubtrobot.jimu.exception.RobotActiveException;
/* loaded from: classes2.dex */
public interface IGlobalExceptionListener {
void onGlobalException(RobotActiveException robotActiveException);
}

View File

@@ -0,0 +1,10 @@
package com.ubtrobot.jimu.robotapi;
import com.ubtrobot.jimu.bluetooth.ConnectionState;
/* loaded from: classes2.dex */
public interface IPowerStateListener {
void onConnectionStateChange(String str, ConnectionState connectionState);
void onPowerStateChanged(BatteryInfo batteryInfo);
}

View File

@@ -0,0 +1,19 @@
package com.ubtrobot.jimu.robotapi;
import com.ubtrobot.jimu.connection.RequestException;
/* loaded from: classes2.dex */
public class JimuException extends RequestException {
public static final int ERR_CODE_ARGUMENT_INVALID = -20;
public static final int ERR_CODE_RESULT_FAIL = -21;
public static final int ERR_CODE_RES_INVALID = -22;
public static final String ERR_MSG_ARGUMENT_INVALID = "Argument is illegal!";
public JimuException(int i, String str) {
this(i, str, null);
}
public JimuException(int i, String str, Throwable th) {
super(i, str, th);
}
}

View File

@@ -0,0 +1,191 @@
package com.ubtrobot.jimu.robotapi;
import android.content.Context;
import com.ubtrobot.jimu.Firmware;
import com.ubtrobot.jimu.bluetooth.ConnectCallback;
import com.ubtrobot.jimu.bluetooth.ConnectionState;
import com.ubtrobot.jimu.bluetooth.ConnectionStateListener;
import com.ubtrobot.jimu.connection.RequestException;
import com.ubtrobot.jimu.connection.RobotConnection;
import com.ubtrobot.jimu.robotapi.UpdateManager;
import java.util.List;
/* loaded from: classes2.dex */
public class JimuManager {
private ServoManager a;
private MotorManager b;
private DeviceManager c;
private SensorManager d;
private UpdateManager e;
private GlobalManager f;
private RobotConnection g;
private String h;
public JimuManager(Context context) {
this.g = new RobotConnection(context);
this.a = new ServoManager(this.g);
this.b = new MotorManager(this.g);
new LedManager(this.g);
this.c = new DeviceManager(this.g);
this.d = new SensorManager(this.g);
this.e = new UpdateManager(context, this.g);
this.f = new GlobalManager(this.g, this.c);
}
public void a(String str, ConnectCallback connectCallback) {
this.g.a(str, connectCallback);
}
public void b(ConnectionStateListener connectionStateListener) {
this.g.b(connectionStateListener);
}
public void c() {
this.g.a();
}
public String d() {
return this.g.b();
}
public String e() {
return this.h;
}
public BatteryInfo f() {
return this.f.a();
}
public boolean g() {
String d = d();
return d != null && a(d) == ConnectionState.STATE_CONNECTED;
}
public boolean h() throws JimuException {
return this.c.a();
}
public void i() throws JimuException {
this.a.b();
}
public String j() throws JimuException {
return this.c.b();
}
public BatteryInfo k() throws JimuException {
return this.c.d();
}
public BoardInfo l() throws JimuException {
return this.c.e();
}
public String m() throws JimuException {
return this.c.f();
}
public int n() throws RequestException {
return this.c.g();
}
public void o() {
this.f.b();
}
public void p() {
this.f.c();
}
public void q() throws JimuException {
this.b.a();
}
public void r() throws JimuException {
this.a.a();
}
public ConnectionState a(String str) {
return this.g.a(str);
}
public ConnectionState b(String str) {
return (!g() || str == null) ? ConnectionState.STATE_DISCONNECTED : !str.equals(e()) ? ConnectionState.STATE_DISCONNECTED : ConnectionState.STATE_CONNECTED;
}
public void c(String str) {
this.h = str;
}
public void a(ConnectionStateListener connectionStateListener) {
this.g.a(connectionStateListener);
}
public boolean a(BoardInfo boardInfo, List<Firmware> list, UpdateManager.UpdateProgressListener updateProgressListener) {
return this.e.a(boardInfo, list, updateProgressListener);
}
public void a() {
this.e.a();
}
public void a(boolean z) throws JimuException {
this.c.a(z);
}
public BatteryInfo a(IPowerStateListener iPowerStateListener) {
return this.f.a(iPowerStateListener);
}
public void a(IGlobalExceptionListener iGlobalExceptionListener) {
this.f.a(iGlobalExceptionListener);
}
public int b() throws JimuException {
return this.e.b();
}
public void a(int[] iArr, float[] fArr, int i, int i2) throws MotorException {
this.a.a(iArr, fArr, i, i2);
}
public void b(IPowerStateListener iPowerStateListener) {
this.f.b(iPowerStateListener);
}
public void a(int[] iArr, int i) throws MotorException {
this.a.a(iArr, i);
}
public void b(IGlobalExceptionListener iGlobalExceptionListener) {
this.f.b(iGlobalExceptionListener);
}
public List<ServoAngleReadInfo> a(int i, boolean z) throws JimuException {
return this.a.a(i, z);
}
public void b(boolean z) {
this.f.a(z);
}
public void a(int[] iArr, int[] iArr2, int[] iArr3) throws MotorException {
this.b.a(iArr, iArr2, iArr3);
}
public ServoAngleReadInfo b(int i, boolean z) throws JimuException {
return this.a.b(i, z);
}
public int a(int i, int i2) throws JimuException {
return this.b.a(i, i2);
}
public int a(int i, List<Integer> list, boolean z) throws JimuException {
return this.d.a(i, list, z);
}
public BluetoothSpeakerInfo a(int i) throws JimuException {
return this.d.a(i);
}
}

View File

@@ -0,0 +1,17 @@
package com.ubtrobot.jimu.robotapi;
import android.content.Context;
import com.ubtrobot.jimu.bluetooth.Cancellable;
import com.ubtrobot.jimu.bluetooth.JimuBluetoothManager;
import com.ubtrobot.jimu.bluetooth.base.discover.ScannedHubEmitter;
/* loaded from: classes2.dex */
public class JimuScanner {
public JimuScanner(Context context) {
JimuBluetoothManager.d().supportsBluetooth(context);
}
public Cancellable a(ScannedHubEmitter scannedHubEmitter, int i) {
return JimuBluetoothManager.d().a(scannedHubEmitter, i);
}
}

View File

@@ -0,0 +1,9 @@
package com.ubtrobot.jimu.robotapi;
import com.ubtrobot.jimu.connection.RobotConnection;
/* loaded from: classes2.dex */
public class LedManager {
public LedManager(RobotConnection robotConnection) {
}
}

View File

@@ -0,0 +1,34 @@
package com.ubtrobot.jimu.robotapi;
import java.util.ArrayList;
/* loaded from: classes2.dex */
public class MotorException extends JimuException {
private ArrayList<Integer> failIds;
private int subErrorId;
public MotorException(int i, String str) {
super(i, str);
}
public ArrayList<Integer> getFailIds() {
return this.failIds;
}
public int getSubErrorId() {
return this.subErrorId;
}
public void setFailIds(ArrayList<Integer> arrayList) {
this.failIds = arrayList;
}
public void setSubErrorId(int i) {
this.subErrorId = i;
}
public MotorException(int i, String str, ArrayList<Integer> arrayList) {
super(i, str);
this.failIds = arrayList;
}
}

View File

@@ -0,0 +1,151 @@
package com.ubtrobot.jimu.robotapi;
import android.util.Log;
import com.ubtrobot.jimu.bluetooth.base.ProtocolPacket;
import com.ubtrobot.jimu.connection.RequestException;
import com.ubtrobot.jimu.connection.RobotConnection;
import java.util.ArrayList;
import java.util.Arrays;
/* loaded from: classes2.dex */
public class MotorManager {
protected RobotConnection a;
public MotorManager(RobotConnection robotConnection) {
this.a = robotConnection;
}
private static byte[] b(int[] iArr, int[] iArr2, int[] iArr3) {
if (iArr.length != iArr2.length || iArr2.length != iArr3.length) {
Log.e("MotorManager", "Invalid arguments!");
return null;
}
int length = iArr.length;
byte[] a = a(iArr);
byte[] bArr = new byte[a.length + (length * 4)];
System.arraycopy(a, 0, bArr, 0, a.length);
int length2 = a.length + 0;
for (int i = 1; i <= length; i++) {
int i2 = length - i;
int i3 = iArr2[i2];
int i4 = length2 + 1;
bArr[length2] = (byte) ((i3 >> 8) & 255);
int i5 = i4 + 1;
bArr[i4] = (byte) (i3 & 255);
int i6 = iArr3[i2];
int i7 = i5 + 1;
bArr[i5] = (byte) ((i6 >> 8) & 255);
length2 = i7 + 1;
bArr[i7] = (byte) (i6 & 255);
}
return bArr;
}
public void a(int[] iArr, int[] iArr2, int[] iArr3) throws MotorException {
int[] iArr4 = new int[iArr3.length];
for (int i = 0; i < iArr3.length; i++) {
iArr4[i] = iArr3[i] / 100;
}
try {
byte[] g = this.a.a(new ProtocolPacket(144, b(iArr, iArr2, iArr4))).g();
if (g[0] == 0) {
return;
}
throw new MotorException(-21, "cmd result is fail! ErrCode:" + ((int) g[0]), a(Arrays.copyOfRange(g, 1, g.length)));
} catch (RequestException e) {
throw new MotorException(e.getCode(), e.getMessage());
}
}
public int a(int i, int i2) throws JimuException {
ProtocolPacket protocolPacket = new ProtocolPacket(116, new byte[]{10, (byte) i, (byte) i2});
try {
byte[] g = this.a.a(protocolPacket).g();
if (g.length == 3) {
return g[2] & 255;
}
throw new JimuException(-22, "res argument is err!");
} catch (RequestException e) {
Log.e("MotorManager", "Call cmd fail! cmd:" + ((int) protocolPacket.f()), e);
throw new JimuException(e.getCode(), e.getMessage());
}
}
public void a() throws JimuException {
try {
byte[] g = this.a.a(new ProtocolPacket(146, new byte[0])).g();
if (g[0] == 0) {
return;
}
throw new JimuException(-21, "cmd result is fail! ErrCode:" + ((int) g[0]));
} catch (RequestException e) {
throw new JimuException(e.getCode(), e.getMessage());
}
}
private static byte[] a(int[] iArr) {
int i;
byte[] bArr = new byte[8];
int i2 = 0;
byte b = 0;
while (true) {
i = 1;
if (i2 >= iArr.length) {
break;
}
if (iArr[i2] > 64 || iArr[i2] < 1) {
Log.e("MotorManager", "Unsupport id! The support motor id range is 1~64");
}
int i3 = (iArr[i2] - 1) / 8;
b = (byte) (b | (1 << i3));
bArr[i3] = (byte) (((byte) (1 << ((iArr[i2] - 1) % 8))) | bArr[i3]);
i2++;
}
int i4 = 0;
for (byte b2 : bArr) {
if (b2 != 0) {
i4++;
}
}
byte[] bArr2 = new byte[i4 + 1];
bArr2[0] = b;
for (int length = bArr.length - 1; length >= 0; length--) {
if (bArr[length] != 0) {
bArr2[i] = bArr[length];
i++;
}
}
return bArr2;
}
private static ArrayList<Integer> a(byte[] bArr) {
ArrayList<Integer> arrayList = new ArrayList<>();
int i = 0;
byte b = bArr[0];
ArrayList arrayList2 = new ArrayList();
for (int i2 = 7; i2 >= 0; i2--) {
if (((1 << i2) & b & 255) != 0) {
arrayList2.add(Integer.valueOf(i2));
}
}
if (arrayList2.size() != bArr.length - 1) {
return arrayList;
}
while (i < arrayList2.size()) {
int intValue = ((Integer) arrayList2.get(i)).intValue();
i++;
arrayList.addAll(a(bArr[i], intValue * 8));
}
return arrayList;
}
private static ArrayList<Integer> a(byte b, int i) {
ArrayList<Integer> arrayList = new ArrayList<>();
for (int i2 = 0; i2 < 8; i2++) {
if ((b & 255 & (1 << i2)) != 0) {
arrayList.add(Integer.valueOf(i2 + 1 + i));
}
}
return arrayList;
}
}

View File

@@ -0,0 +1,25 @@
package com.ubtrobot.jimu.robotapi;
/* loaded from: classes2.dex */
public interface PeripheralType {
public static final int ATMOSPHERIC_PRESSURE = 97;
public static final int COLOR = 9;
public static final int COMPASS = 96;
public static final int DIGITALTUBE = 7;
public static final int EN_LIGHT_SENSOR = 12;
public static final int FIREBOT_HEAD_LED = 101;
public static final int GRAVITY = 5;
public static final int GYRO = 3;
public static final int INFRARED = 1;
public static final int INVALID_PERIPHERAL_TYPE = -1;
public static final int LED = 4;
public static final int MOTOR = 10;
public static final int New_MAIN_BOARD = 113;
public static final int OLD_MAIN_BOARD = 112;
public static final int RGB_LED = 14;
public static final int SERVO = 128;
public static final int SPEAKER = 8;
public static final int TEMP = 11;
public static final int TOUCH = 2;
public static final int ULTRASOUND = 6;
}

View File

@@ -0,0 +1,130 @@
package com.ubtrobot.jimu.robotapi;
/* loaded from: classes2.dex */
public final class R$string {
public static final int abc_action_bar_home_description = 2131820553;
public static final int abc_action_bar_up_description = 2131820554;
public static final int abc_action_menu_overflow_description = 2131820555;
public static final int abc_action_mode_done = 2131820556;
public static final int abc_activity_chooser_view_see_all = 2131820557;
public static final int abc_activitychooserview_choose_application = 2131820558;
public static final int abc_capital_off = 2131820559;
public static final int abc_capital_on = 2131820560;
public static final int abc_font_family_body_1_material = 2131820561;
public static final int abc_font_family_body_2_material = 2131820562;
public static final int abc_font_family_button_material = 2131820563;
public static final int abc_font_family_caption_material = 2131820564;
public static final int abc_font_family_display_1_material = 2131820565;
public static final int abc_font_family_display_2_material = 2131820566;
public static final int abc_font_family_display_3_material = 2131820567;
public static final int abc_font_family_display_4_material = 2131820568;
public static final int abc_font_family_headline_material = 2131820569;
public static final int abc_font_family_menu_material = 2131820570;
public static final int abc_font_family_subhead_material = 2131820571;
public static final int abc_font_family_title_material = 2131820572;
public static final int abc_menu_alt_shortcut_label = 2131820573;
public static final int abc_menu_ctrl_shortcut_label = 2131820574;
public static final int abc_menu_delete_shortcut_label = 2131820575;
public static final int abc_menu_enter_shortcut_label = 2131820576;
public static final int abc_menu_function_shortcut_label = 2131820577;
public static final int abc_menu_meta_shortcut_label = 2131820578;
public static final int abc_menu_shift_shortcut_label = 2131820579;
public static final int abc_menu_space_shortcut_label = 2131820580;
public static final int abc_menu_sym_shortcut_label = 2131820581;
public static final int abc_prepend_shortcut_label = 2131820582;
public static final int abc_search_hint = 2131820583;
public static final int abc_searchview_description_clear = 2131820584;
public static final int abc_searchview_description_query = 2131820585;
public static final int abc_searchview_description_search = 2131820586;
public static final int abc_searchview_description_submit = 2131820587;
public static final int abc_searchview_description_voice = 2131820588;
public static final int abc_shareactionprovider_share_with = 2131820589;
public static final int abc_shareactionprovider_share_with_application = 2131820590;
public static final int abc_toolbar_collapse_description = 2131820591;
public static final int app_name = 2131820649;
public static final int batter_high = 2131820668;
public static final int batter_low = 2131820669;
public static final int com_crashlytics_android_build_id = 2131820749;
public static final int com_facebook_device_auth_instructions = 2131820750;
public static final int com_facebook_image_download_unknown_error = 2131820751;
public static final int com_facebook_internet_permission_error_message = 2131820752;
public static final int com_facebook_internet_permission_error_title = 2131820753;
public static final int com_facebook_like_button_liked = 2131820754;
public static final int com_facebook_like_button_not_liked = 2131820755;
public static final int com_facebook_loading = 2131820756;
public static final int com_facebook_loginview_cancel_action = 2131820757;
public static final int com_facebook_loginview_log_in_button = 2131820758;
public static final int com_facebook_loginview_log_in_button_continue = 2131820759;
public static final int com_facebook_loginview_log_in_button_long = 2131820762;
public static final int com_facebook_loginview_log_out_action = 2131820763;
public static final int com_facebook_loginview_log_out_button = 2131820766;
public static final int com_facebook_loginview_logged_in_as = 2131820769;
public static final int com_facebook_loginview_logged_in_using_facebook = 2131820772;
public static final int com_facebook_send_button_text = 2131820775;
public static final int com_facebook_share_button_text = 2131820778;
public static final int com_facebook_smart_device_instructions = 2131820781;
public static final int com_facebook_smart_device_instructions_or = 2131820782;
public static final int com_facebook_smart_login_confirmation_cancel = 2131820783;
public static final int com_facebook_smart_login_confirmation_continue_as = 2131820786;
public static final int com_facebook_smart_login_confirmation_title = 2131820789;
public static final int com_facebook_tooltip_default = 2131820792;
public static final int comm_cancel = 2131820797;
public static final int comm_ok = 2131820798;
public static final int common_google_play_services_enable_button = 2131820814;
public static final int common_google_play_services_enable_text = 2131820815;
public static final int common_google_play_services_enable_title = 2131820816;
public static final int common_google_play_services_install_button = 2131820817;
public static final int common_google_play_services_install_text = 2131820818;
public static final int common_google_play_services_install_title = 2131820819;
public static final int common_google_play_services_notification_channel_name = 2131820820;
public static final int common_google_play_services_notification_ticker = 2131820821;
public static final int common_google_play_services_unknown_issue = 2131820822;
public static final int common_google_play_services_unsupported_text = 2131820823;
public static final int common_google_play_services_update_button = 2131820824;
public static final int common_google_play_services_update_text = 2131820825;
public static final int common_google_play_services_update_title = 2131820826;
public static final int common_google_play_services_updating_text = 2131820827;
public static final int common_google_play_services_wear_update_text = 2131820828;
public static final int common_open_on_phone = 2131820829;
public static final int common_signin_button_text = 2131820830;
public static final int common_signin_button_text_long = 2131820831;
public static final int engine_protect_electricity = 2131820978;
public static final int engine_protect_encrypt = 2131820979;
public static final int engine_protect_lock = 2131820980;
public static final int engine_protect_motor_lock = 2131820981;
public static final int engine_protect_motor_other = 2131820982;
public static final int engine_protect_other = 2131820983;
public static final int engine_protect_temp = 2131820984;
public static final int jg_channel_name_p_default = 2131821170;
public static final int jg_channel_name_p_high = 2131821171;
public static final int jg_channel_name_p_low = 2131821172;
public static final int jg_channel_name_p_min = 2131821173;
public static final int kit_name = 2131821184;
public static final int messenger_send_button_text = 2131821253;
public static final int search_menu_title = 2131821508;
public static final int status_bar_notification_info_overflow = 2131821607;
public static final int tw__allow_btn_txt = 2131821703;
public static final int tw__composer_hint = 2131821704;
public static final int tw__install = 2131821705;
public static final int tw__like_tweet = 2131821706;
public static final int tw__liked_tweet = 2131821707;
public static final int tw__loading_tweet = 2131821708;
public static final int tw__login_btn_txt = 2131821709;
public static final int tw__max_tweet_chars = 2131821710;
public static final int tw__not_now_btn_txt = 2131821711;
public static final int tw__pause = 2131821712;
public static final int tw__play = 2131821713;
public static final int tw__play_store = 2131821714;
public static final int tw__post_tweet = 2131821715;
public static final int tw__relative_date_format_long = 2131821716;
public static final int tw__relative_date_format_short = 2131821717;
public static final int tw__replay = 2131821718;
public static final int tw__retweeted_by_format = 2131821719;
public static final int tw__share_content_format = 2131821720;
public static final int tw__share_email_desc = 2131821721;
public static final int tw__share_email_title = 2131821722;
public static final int tw__share_subject_format = 2131821723;
public static final int tw__share_tweet = 2131821724;
public static final int tw__tweet_content_description = 2131821725;
public static final int tw__tweet_media = 2131821726;
}

View File

@@ -0,0 +1,77 @@
package com.ubtrobot.jimu.robotapi;
import android.util.Log;
import com.ubtrobot.jimu.bluetooth.base.ProtocolPacket;
import com.ubtrobot.jimu.connection.RequestException;
import com.ubtrobot.jimu.connection.RobotConnection;
import java.util.Iterator;
import java.util.List;
/* loaded from: classes2.dex */
public class SensorManager {
private RobotConnection a;
public SensorManager(RobotConnection robotConnection) {
this.a = robotConnection;
}
public int a(int i, List<Integer> list, boolean z) throws JimuException {
ProtocolPacket protocolPacket = new ProtocolPacket(113, new byte[]{(byte) (i & 255), a(list), !z ? 1 : 0});
try {
byte[] g = this.a.a(protocolPacket).g();
if (g.length == 3) {
return g[2] & 255;
}
throw new JimuException(-22, "res argument is err!");
} catch (RequestException e) {
Log.e("SensorManager", "Call cmd fail! cmd:" + ((int) protocolPacket.f()), e);
throw new JimuException(e.getCode(), e.getMessage());
}
}
public byte a(List<Integer> list) {
Iterator<Integer> it = list.iterator();
byte b = 0;
while (it.hasNext()) {
b = (byte) (b | (1 << (it.next().intValue() - 1)));
}
return b;
}
public BluetoothSpeakerInfo a(int i) throws JimuException {
if (i >= 1 && i <= 8) {
ProtocolPacket protocolPacket = new ProtocolPacket(114, new byte[]{8, (byte) (1 << (i - 1))});
try {
byte[] g = this.a.a(protocolPacket).g();
int i2 = 3;
if (g.length > 3) {
StringBuilder sb = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
int i3 = 0;
while (i2 < g.length) {
if (i3 < 6) {
sb2.append(String.format("%02x:", Byte.valueOf(g[i2])));
} else {
sb.append((char) g[i2]);
}
i2++;
i3++;
}
if (sb2.length() == 0) {
Log.e("SensorManager", "Read speaker info fail! Mac is null!");
return null;
}
sb2.deleteCharAt(sb2.length() - 1);
return new BluetoothSpeakerInfo(sb2.toString(), sb.toString());
}
Log.e("SensorManager", "Read speaker info fail!");
throw new JimuException(-21, "Read speaker info fail!");
} catch (RequestException e) {
Log.e("SensorManager", "Call cmd fail! cmd:" + ((int) protocolPacket.f()), e);
throw new JimuException(e.getCode(), e.getMessage());
}
}
Log.e("SensorManager", "Invalid id");
throw new JimuException(-20, JimuException.ERR_MSG_ARGUMENT_INVALID);
}
}

View File

@@ -0,0 +1,40 @@
package com.ubtrobot.jimu.robotapi;
/* loaded from: classes2.dex */
public class ServoAngleReadInfo {
private int a;
private float b;
private boolean c;
private float d;
public ServoAngleReadInfo(int i, boolean z, float f, float f2) {
this.a = i;
this.c = z;
this.d = f;
this.b = f2;
}
public float a() {
return this.b;
}
public int b() {
return this.a;
}
public float c() {
return this.d;
}
public String toString() {
return "ServoAngleReadInfo{id=" + this.a + ", actualAngle=" + this.b + ", isReciveSuccess=" + this.c + ", targetAngle=" + this.d + '}';
}
public void a(float f) {
this.b = f;
}
public void b(float f) {
this.d = f;
}
}

View File

@@ -0,0 +1,242 @@
package com.ubtrobot.jimu.robotapi;
import android.util.Log;
import com.ubtrobot.jimu.bluetooth.base.IPacket;
import com.ubtrobot.jimu.bluetooth.base.ProtocolPacket;
import com.ubtrobot.jimu.connection.RequestException;
import com.ubtrobot.jimu.connection.ResponseCallback;
import com.ubtrobot.jimu.connection.RobotConnection;
import com.ubtrobot.log.ALog;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/* loaded from: classes2.dex */
public class ServoManager extends MotorManager {
public ServoManager(RobotConnection robotConnection) {
super(robotConnection);
}
public void a(int[] iArr, float[] fArr, int i, int i2) throws MotorException {
int length = fArr.length;
byte[] bArr = new byte[length + 4 + 1 + 2];
byte[] a = a(iArr);
byte[] bArr2 = new byte[length];
for (int i3 = 0; i3 < length; i3++) {
bArr2[i3] = (byte) fArr[i3];
}
System.arraycopy(a, 0, bArr, 0, a.length);
int length2 = a.length + 0;
System.arraycopy(bArr2, 0, bArr, length2, bArr2.length);
int length3 = length2 + bArr2.length;
bArr[length3] = (byte) (i / 20);
int i4 = length3 + 1;
int i5 = i + i2;
bArr[i4] = (byte) ((65280 & i5) >> 8);
bArr[i4 + 1] = (byte) (i5 & 255);
try {
byte[] g = this.a.a(new ProtocolPacket(9, bArr)).g();
if (g.length == 1 && g[0] == 0) {
return;
}
if (g.length != 5) {
throw new MotorException(-21, "cmd result is fail! ErrCode:" + ((int) g[0]));
}
throw new MotorException(-21, "cmd result is fail! ErrCode:" + ((int) g[0]), a(Arrays.copyOfRange(g, 1, g.length)));
} catch (RequestException e) {
throw new MotorException(e.getCode(), e.getMessage());
}
}
public void b() throws JimuException {
b(0, false);
}
public ServoAngleReadInfo b(int i, boolean z) throws JimuException {
new ArrayList();
byte[] bArr = new byte[2];
bArr[0] = (byte) i;
boolean z2 = true;
if (z) {
bArr[1] = 1;
} else {
bArr[1] = 0;
}
ProtocolPacket protocolPacket = new ProtocolPacket(11, bArr);
try {
byte[] g = this.a.a(protocolPacket).g();
if (g.length == 1 || g.length != 6) {
throw new JimuException(-22, "Control fail!");
}
int i2 = g[0] & 255;
if ((g[1] & 255) != 170) {
z2 = false;
}
return new ServoAngleReadInfo(i2, z2, ((g[2] & 255) << 8) | (g[3] & 255), (g[5] & 255) | ((g[4] & 255) << 8));
} catch (RequestException e) {
Log.e("ServoManager", "Call cmd fail! cmd:" + ((int) protocolPacket.f()), e);
throw new JimuException(e.getCode(), e.getMessage());
}
}
public void a(int[] iArr, int i) throws MotorException {
int length = iArr.length;
byte[] bArr = new byte[length + 4];
bArr[0] = (byte) (length & 255);
int i2 = 0;
while (i2 < length) {
int i3 = i2 + 1;
bArr[i3] = (byte) iArr[i2];
i2 = i3;
}
if (i > 0) {
bArr[length + 1] = 1;
} else if (i < 0) {
bArr[length + 1] = 2;
} else {
bArr[length + 1] = 0;
}
int abs = Math.abs(i);
bArr[length + 2] = (byte) ((65280 & abs) >> 8);
bArr[length + 3] = (byte) (abs & 255);
try {
byte[] g = this.a.a(new ProtocolPacket(7, bArr)).g();
if (g.length == 1 && g[0] == 0) {
return;
}
if (g.length == 5) {
throw new MotorException(-21, "cmd result is fail! ErrCode:" + ((int) g[0]), a(Arrays.copyOfRange(g, 1, g.length)));
}
throw new MotorException(-21, "cmd result is fail! ErrCode:" + ((int) g[0]));
} catch (RequestException e) {
throw new MotorException(e.getCode(), e.getMessage());
}
}
@Override // com.ubtrobot.jimu.robotapi.MotorManager
public void a() throws JimuException {
try {
byte[] g = this.a.a(new ProtocolPacket(59, new byte[0])).g();
if (g[0] == 0) {
return;
}
throw new JimuException(-21, "cmd result is fail! ErrCode:" + ((int) g[0]));
} catch (RequestException e) {
throw new JimuException(e.getCode(), e.getMessage());
}
}
public List<ServoAngleReadInfo> a(final int i, boolean z) throws JimuException {
final boolean[] zArr = new boolean[1];
final boolean[] zArr2 = new boolean[1];
final JimuException[] jimuExceptionArr = new JimuException[1];
final ArrayList arrayList = new ArrayList();
byte[] bArr = new byte[2];
bArr[0] = 0;
if (z) {
bArr[1] = 1;
} else {
bArr[1] = 0;
}
ProtocolPacket protocolPacket = new ProtocolPacket(11, bArr);
this.a.a(protocolPacket, new ResponseCallback(this) { // from class: com.ubtrobot.jimu.robotapi.ServoManager.1
@Override // com.ubtrobot.jimu.connection.ResponseCallback
public void a(IPacket iPacket, IPacket iPacket2) {
byte[] g = iPacket2.g();
if (g.length == 1 || g.length != 6) {
synchronized (zArr) {
jimuExceptionArr[0] = new JimuException(-22, "Control fail!");
zArr[0] = true;
ALog.a("ServoManager").d("responded notify");
zArr.notifyAll();
}
return;
}
ServoAngleReadInfo servoAngleReadInfo = new ServoAngleReadInfo(g[0] & 255, (g[1] & 255) == 170, ((g[2] & 255) << 8) | (g[3] & 255), (g[5] & 255) | ((g[4] & 255) << 8));
synchronized (zArr) {
arrayList.add(servoAngleReadInfo);
if (arrayList.size() == i) {
zArr2[0] = true;
zArr[0] = true;
Log.d("ServoManager", "responded notify");
zArr.notifyAll();
}
}
}
@Override // com.ubtrobot.jimu.connection.ResponseCallback
public void a(IPacket iPacket, RequestException requestException) {
synchronized (zArr) {
jimuExceptionArr[0] = new JimuException(requestException.getCode(), requestException.getMessage());
zArr[0] = true;
Log.d("ServoManager", "responded notify");
zArr.notifyAll();
}
}
}, i);
synchronized (zArr) {
while (!zArr[0]) {
try {
Log.d("ServoManager", "responded wait");
zArr.wait();
break;
} catch (InterruptedException e) {
Log.w("ServoManager", "Interrupted by someone when sync doRequest. req=" + protocolPacket + "Ignore it.", e);
Thread.currentThread().interrupt();
}
}
if (jimuExceptionArr[0] != null) {
throw jimuExceptionArr[0];
}
}
return arrayList;
}
@Override // com.ubtrobot.jimu.robotapi.MotorManager
public int a(int i, int i2) throws JimuException {
ProtocolPacket protocolPacket = new ProtocolPacket(12, new byte[]{(byte) i, (byte) i2});
try {
byte[] g = this.a.a(protocolPacket).g();
if (g.length == 1) {
return g[0] & 255;
}
throw new JimuException(-22, "res argument is err!");
} catch (RequestException e) {
Log.e("ServoManager", "Call cmd fail! cmd:" + ((int) protocolPacket.f()), e);
throw new JimuException(e.getCode(), e.getMessage());
}
}
private byte[] a(int[] iArr) {
byte[] bArr = new byte[4];
for (int i : iArr) {
if (i > 0 && i <= 8) {
bArr[3] = (byte) (bArr[3] + (1 << (i - 1)));
} else if (i > 8 && i <= 16) {
bArr[2] = (byte) (bArr[2] + (1 << ((i - 1) - 8)));
} else if (i > 16 && i <= 24) {
bArr[1] = (byte) (bArr[1] + (1 << ((i - 1) - 16)));
} else if (i >= 24 && i <= 32) {
bArr[0] = (byte) (bArr[0] + (1 << ((i - 1) - 24)));
}
}
return bArr;
}
private ArrayList<Integer> a(byte[] bArr) {
ArrayList<Integer> arrayList = new ArrayList<>();
if (bArr.length != 4) {
return arrayList;
}
for (int i = 0; i < bArr.length; i++) {
int i2 = 24 - (i * 8);
byte b = bArr[i];
for (int i3 = 0; i3 < 8; i3++) {
if ((b & 255 & (1 << i3)) != 0) {
arrayList.add(Integer.valueOf(i3 + 1 + i2));
}
}
}
return arrayList;
}
}

View File

@@ -0,0 +1,989 @@
package com.ubtrobot.jimu.robotapi;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import com.ijm.dataencryption.de.DataDecryptTool;
import com.ubtech.utils.FileHelper;
import com.ubtech.utils.XLog;
import com.ubtrobot.jimu.Firmware;
import com.ubtrobot.jimu.bluetooth.Cancellable;
import com.ubtrobot.jimu.bluetooth.ConnectCallback;
import com.ubtrobot.jimu.bluetooth.base.IPacket;
import com.ubtrobot.jimu.bluetooth.base.ProtocolPacket;
import com.ubtrobot.jimu.bluetooth.base.discover.ScanResult;
import com.ubtrobot.jimu.bluetooth.base.discover.ScannedHubEmitter;
import com.ubtrobot.jimu.connection.PacketsReceiveListener;
import com.ubtrobot.jimu.connection.RequestException;
import com.ubtrobot.jimu.connection.RobotConnection;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Timer;
/* loaded from: classes2.dex */
public class UpdateManager implements PacketsReceiveListener, ConnectCallback {
private Timer a;
private volatile int b;
private RobotConnection c;
private DeviceManager d;
private JimuScanner e;
private Cancellable f;
private List<Firmware> g = new ArrayList();
private Queue<Firmware> h = new LinkedList();
private Firmware i;
private Firmware j;
private Firmware k;
private UpdateProgressListener l;
private int m;
private HandlerThread n;
private Handler o;
private volatile boolean p;
private int q;
private BoardInfo r;
public static class UpdateException extends RequestException {
public static final int ERR_CODE_DISCONNECTED = -99;
public static final int ERR_CODE_LOW_POWER = -102;
public static final int ERR_CODE_NO_FIRMWARE = -101;
public static final int ERR_CODE_STOP_UPDATE_BOARD_FAILED = -107;
public static final int ERR_CODE_UPDATE_BOARD_FAILED = -103;
public static final int ERR_CODE_UPDATE_CANCEL = -106;
public static final int ERR_CODE_UPDATE_FAILED = -100;
public static final int ERR_CODE_UPDATE_SENSOR_FAILED = -105;
public static final int ERR_CODE_UPDATE_SERVO_FAILED = -104;
private final IPacket response;
public UpdateException(int i, String str) {
this(i, str, null, null);
}
public IPacket getResponse() {
return this.response;
}
public UpdateException(int i, String str, IPacket iPacket) {
this(i, str, null, iPacket);
}
public UpdateException(int i, String str, Throwable th) {
this(i, str, th, null);
}
public UpdateException(int i, String str, Throwable th, IPacket iPacket) {
super(i, str, th);
this.response = iPacket;
}
}
public interface UpdateProgressListener {
void a(int i);
void a(int i, int i2);
void a(int i, Object obj);
void a(UpdateException updateException);
void g(BoardInfo boardInfo);
}
public UpdateManager(Context context, RobotConnection robotConnection) {
this.c = robotConnection;
this.d = new DeviceManager(robotConnection);
this.e = new JimuScanner(context.getApplicationContext());
}
private byte[] a(long j) {
return new byte[]{(byte) (j & 255), (byte) ((j >> 8) & 255), (byte) ((j >> 16) & 255), (byte) ((j >> 24) & 255)};
}
private byte[] b(int i) {
return new byte[]{(byte) (i & 255), (byte) ((i >> 8) & 255)};
}
@Override // com.ubtrobot.jimu.bluetooth.ConnectCallback
public void onSuccess() {
c(7);
}
private void d() {
XLog.a("UpdateManager", "quit update cancel=" + this.p);
try {
if (this.n != null) {
this.n.quit();
this.n = null;
this.o = null;
}
if (this.f == null || this.f.isCancelled()) {
return;
}
this.f.cancel();
this.f = null;
} catch (Exception e) {
e.printStackTrace();
}
}
private void e(String str, IPacket iPacket) {
byte[] g = iPacket.g();
if (g == null || g.length < 2) {
a(new UpdateException(UpdateException.ERR_CODE_UPDATE_SENSOR_FAILED, "83指令返回异常"));
return;
}
int i = g[1] & 255;
Log.d("UpdateManager", String.format("%s指令返回%s", "83", Integer.toHexString(i)));
if (i == 0) {
a(this.k.c(), 100);
return;
}
if (i == 170) {
this.c.a(true);
a(this.k.c(), (Object) null);
c(3);
} else {
a(new UpdateException(UpdateException.ERR_CODE_UPDATE_SENSOR_FAILED, "83指令返回异常传感器升级失败:" + i, iPacket));
}
}
/* JADX INFO: Access modifiers changed from: private */
public void f() {
String b = this.c.b();
if (TextUtils.isEmpty(b)) {
a(new UpdateException(UpdateException.ERR_CODE_UPDATE_BOARD_FAILED, "新主板升级失败mac地址为null"));
} else {
this.c.a(b, this);
}
}
private int g() throws JimuException {
int a = a(new ProtocolPacket(130, new byte[]{0}));
XLog.a("UpdateManager", "取消传感器升级:" + a);
return a;
}
private int h() throws JimuException {
int a = a(new ProtocolPacket(37, new byte[]{0}));
XLog.a("UpdateManager", "取消舵机升级:" + a);
return a;
}
/* JADX INFO: Access modifiers changed from: private */
public void i() {
this.f = this.e.a(new ScannedHubEmitter() { // from class: com.ubtrobot.jimu.robotapi.UpdateManager.2
@Override // com.ubtrobot.jimu.bluetooth.base.discover.ScannedHubEmitter
public void a() {
}
@Override // com.ubtrobot.jimu.bluetooth.base.discover.ScannedHubEmitter
public void a(int i, String str) {
}
@Override // com.ubtrobot.jimu.bluetooth.base.discover.ScannedHubEmitter
public void a(ScanResult scanResult) {
if (scanResult == null || scanResult.a() == null || TextUtils.isEmpty(scanResult.a().getAddress()) || !scanResult.a().getAddress().equals(UpdateManager.this.c.b())) {
return;
}
XLog.a("UpdateManager", "新主板升级,扫描到设备,准备开始重连...");
UpdateManager.this.c(6);
UpdateManager.this.f.cancel();
}
}, 60000);
}
/* JADX INFO: Access modifiers changed from: private */
/* JADX WARN: Code restructure failed: missing block: B:30:0x007b, code lost:
android.util.Log.d("UpdateManager", "total:" + (java.lang.System.currentTimeMillis() - r13) + " sleep: " + r11);
*/
/* JADX WARN: Code restructure failed: missing block: B:31:0x009d, code lost:
if (r16 == false) goto L34;
*/
/* JADX WARN: Code restructure failed: missing block: B:32:0x009f, code lost:
a(new com.ubtrobot.jimu.robotapi.UpdateManager.UpdateException(com.ubtrobot.jimu.robotapi.UpdateManager.UpdateException.ERR_CODE_UPDATE_BOARD_FAILED, "主板升级失败指令1C失败"));
*/
/* JADX WARN: Code restructure failed: missing block: B:33:0x00a9, code lost:
return;
*/
/* JADX WARN: Code restructure failed: missing block: B:34:0x00aa, code lost:
b(20L);
*/
/* JADX WARN: Code restructure failed: missing block: B:35:0x00af, code lost:
if (r19.p == false) goto L37;
*/
/* JADX WARN: Code restructure failed: missing block: B:36:0x00b1, code lost:
return;
*/
/* JADX WARN: Code restructure failed: missing block: B:38:0x00b6, code lost:
if (a(r4, r7) == 0) goto L41;
*/
/* JADX WARN: Code restructure failed: missing block: B:39:0x00b8, code lost:
a(new com.ubtrobot.jimu.robotapi.UpdateManager.UpdateException(com.ubtrobot.jimu.robotapi.UpdateManager.UpdateException.ERR_CODE_STOP_UPDATE_BOARD_FAILED, "主板升级失败指令1B失败"));
*/
/* JADX WARN: Code restructure failed: missing block: B:40:0x00c4, code lost:
return;
*/
/* JADX WARN: Code restructure failed: missing block: B:42:0x00cd, code lost:
if (r19.i.c() != 113) goto L47;
*/
/* JADX WARN: Code restructure failed: missing block: B:43:0x00cf, code lost:
a(r19.i.c(), 100);
com.ubtech.utils.XLog.a("UpdateManager", "新主板升级文件传输完毕等待60秒重连");
r19.q = 0;
*/
/* JADX WARN: Code restructure failed: missing block: B:44:0x00e1, code lost:
if (r19.o == null) goto L46;
*/
/* JADX WARN: Code restructure failed: missing block: B:45:0x00e3, code lost:
r19.o.sendMessageDelayed(r19.o.obtainMessage(5), 50000);
*/
/* JADX WARN: Code restructure failed: missing block: B:46:?, code lost:
return;
*/
/* JADX WARN: Code restructure failed: missing block: B:47:0x00f3, code lost:
a(new com.ubtrobot.jimu.robotapi.UpdateManager.UpdateException(com.ubtrobot.jimu.robotapi.UpdateManager.UpdateException.ERR_CODE_UPDATE_BOARD_FAILED, "mHandler=null"));
*/
/* JADX WARN: Code restructure failed: missing block: B:48:?, code lost:
return;
*/
/* JADX WARN: Code restructure failed: missing block: B:49:0x00fe, code lost:
r19.c.a(false);
*/
/* JADX WARN: Code restructure failed: missing block: B:50:?, code lost:
return;
*/
/*
Code decompiled incorrectly, please refer to instructions dump.
To view partially-correct code enable 'Show inconsistent code' option in preferences
*/
public void j() {
/*
Method dump skipped, instructions count: 272
To view this dump change 'Code comments level' option to 'DEBUG'
*/
throw new UnsupportedOperationException("Method not decompiled: com.ubtrobot.jimu.robotapi.UpdateManager.j():void");
}
/* JADX INFO: Access modifiers changed from: private */
/* JADX WARN: Code restructure failed: missing block: B:47:0x00d6, code lost:
if (r5 == false) goto L48;
*/
/* JADX WARN: Code restructure failed: missing block: B:48:0x00d8, code lost:
a(new com.ubtrobot.jimu.robotapi.UpdateManager.UpdateException(com.ubtrobot.jimu.robotapi.UpdateManager.UpdateException.ERR_CODE_UPDATE_SERVO_FAILED, "舵机升级失败指令24失败"));
*/
/* JADX WARN: Code restructure failed: missing block: B:49:0x00e2, code lost:
return;
*/
/* JADX WARN: Code restructure failed: missing block: B:50:0x00e3, code lost:
b(20L);
*/
/* JADX WARN: Code restructure failed: missing block: B:51:0x00e8, code lost:
if (r11.p == false) goto L51;
*/
/* JADX WARN: Code restructure failed: missing block: B:52:0x00ea, code lost:
return;
*/
/* JADX WARN: Code restructure failed: missing block: B:54:0x00ef, code lost:
if (b(r1, r2) == 0) goto L54;
*/
/* JADX WARN: Code restructure failed: missing block: B:55:0x00f1, code lost:
a(new com.ubtrobot.jimu.robotapi.UpdateManager.UpdateException(com.ubtrobot.jimu.robotapi.UpdateManager.UpdateException.ERR_CODE_UPDATE_SERVO_FAILED, "舵机升级失败指令26失败"));
*/
/* JADX WARN: Code restructure failed: missing block: B:56:0x00fb, code lost:
r11.c.a(false);
*/
/* JADX WARN: Code restructure failed: missing block: B:57:?, code lost:
return;
*/
/*
Code decompiled incorrectly, please refer to instructions dump.
To view partially-correct code enable 'Show inconsistent code' option in preferences
*/
public void k() {
/*
Method dump skipped, instructions count: 269
To view this dump change 'Code comments level' option to 'DEBUG'
*/
throw new UnsupportedOperationException("Method not decompiled: com.ubtrobot.jimu.robotapi.UpdateManager.k():void");
}
private void b(String str, IPacket iPacket) {
int i = iPacket.g()[0] & 255;
Log.d("UpdateManager", String.format("%s指令返回%s", "1E", Integer.toHexString(i)));
if (i == 0) {
a(this.i.c(), 100);
return;
}
if (i == 1) {
a(new UpdateException(UpdateException.ERR_CODE_UPDATE_BOARD_FAILED, "老主控开始升级失败"));
return;
}
if (i == 170) {
a(new UpdateException(UpdateException.ERR_CODE_UPDATE_BOARD_FAILED, "老主控开始还原主程序"));
} else if (i != 238) {
a(new UpdateException(UpdateException.ERR_CODE_UPDATE_BOARD_FAILED, "老主控开始升级失败"));
} else {
a(new UpdateException(UpdateException.ERR_CODE_UPDATE_BOARD_FAILED, "老主控开始还原失败"));
}
}
/* JADX INFO: Access modifiers changed from: private */
public void c() {
XLog.a("UpdateManager", "cancel update");
this.c.b(this);
try {
try {
if (this.m == 3) {
g();
} else if (this.m == 2) {
h();
} else if (this.m == 1) {
b();
}
} catch (Exception e) {
e.printStackTrace();
}
} finally {
d();
}
}
public boolean a(BoardInfo boardInfo) {
return boardInfo == null || boardInfo.c() != 0 || boardInfo.b() >= 7.4f;
}
public boolean a(BoardInfo boardInfo, List<Firmware> list, UpdateProgressListener updateProgressListener) {
this.m = 0;
this.l = updateProgressListener;
if (list != null && list.size() != 0) {
if (!a(boardInfo)) {
this.p = true;
a(new UpdateException(UpdateException.ERR_CODE_LOW_POWER, "电量过低(电池电压低于7.4V)"));
return false;
}
this.r = boardInfo;
this.i = null;
this.j = null;
this.h.clear();
this.g.clear();
this.g.addAll(list);
for (Firmware firmware : list) {
if (112 != firmware.c() && 113 != firmware.c()) {
if (128 == firmware.c()) {
this.j = firmware;
} else {
this.h.add(firmware);
}
} else {
this.i = firmware;
}
}
this.c.a(this);
this.p = false;
this.n = new HandlerThread("jimu_firmware_update_thread");
this.n.start();
this.o = new Handler(this.n.getLooper()) { // from class: com.ubtrobot.jimu.robotapi.UpdateManager.1
@Override // android.os.Handler
public void handleMessage(Message message) {
super.handleMessage(message);
try {
switch (message.what) {
case 1:
UpdateManager.this.j();
break;
case 2:
UpdateManager.this.k();
break;
case 3:
UpdateManager.this.a(true);
break;
case 4:
UpdateManager.this.c();
break;
case 5:
UpdateManager.this.m = 5;
UpdateManager.this.i();
break;
case 6:
UpdateManager.this.m = 6;
UpdateManager.this.f();
break;
case 7:
UpdateManager.this.m = 7;
UpdateManager.this.e();
break;
}
} catch (Exception e) {
e.printStackTrace();
UpdateManager.this.a(new UpdateException(-100, "升级失败", e));
}
}
};
c(1);
return true;
}
a(new UpdateException(UpdateException.ERR_CODE_NO_FIRMWARE, "需要升级的固件列表为null"));
return false;
}
private int b(byte[] bArr, int i, int i2) throws JimuException {
return a(new ProtocolPacket(28, a(bArr, i, i2)));
}
private void d(String str, IPacket iPacket) {
int i = iPacket.g()[0] & 255;
Log.d("UpdateManager", String.format("%s指令返回%s", "26", Integer.toHexString(i)));
if (i == 0) {
a(PeripheralType.SERVO, 100);
return;
}
if (i == 2) {
a(new UpdateException(UpdateException.ERR_CODE_UPDATE_SERVO_FAILED, "舵机升级失败: " + iPacket.g(), iPacket));
return;
}
if (i != 170) {
a(new UpdateException(UpdateException.ERR_CODE_UPDATE_SERVO_FAILED, "舵机升级失败", iPacket));
} else {
this.c.a(true);
c(3);
}
}
/* JADX INFO: Access modifiers changed from: private */
public void e() {
try {
this.d.g();
b(20L);
BoardInfo e = this.d.e();
if (e == null) {
b(2000L);
e = this.d.e();
}
if (e != null && !TextUtils.isEmpty(e.d())) {
if (!e.d().equals(this.i.d())) {
a(new UpdateException(UpdateException.ERR_CODE_UPDATE_BOARD_FAILED, "新主板升级,重连后版本信息和要升级的不一致,升级失败"));
return;
}
Log.d("UpdateManager", "新主板升级成功,现在的版本名称为:" + e.d());
a(this.i.c(), e);
c(2);
this.r = e;
return;
}
a(new UpdateException(UpdateException.ERR_CODE_UPDATE_BOARD_FAILED, "新主板升级,重连后读取主板信息失败"));
} catch (Exception e2) {
e2.printStackTrace();
a(new UpdateException(UpdateException.ERR_CODE_UPDATE_BOARD_FAILED, "新主板升级,重连后读取主板信息失败"));
}
}
public int b() throws JimuException {
int a = a(new ProtocolPacket(29, new byte[]{0}));
XLog.a("UpdateManager", "取消主板升级:" + a);
return a;
}
private void c(String str, IPacket iPacket) {
int i = iPacket.g()[0] & 255;
Log.d("UpdateManager", String.format("%s指令返回%s", "1F", Integer.toHexString(i)));
if (i == 0) {
this.c.a(true);
c(2);
} else {
if (i == 1) {
a(new UpdateException(UpdateException.ERR_CODE_UPDATE_BOARD_FAILED, "主控结束升级失败"));
return;
}
if (i == 170) {
a(new UpdateException(UpdateException.ERR_CODE_UPDATE_BOARD_FAILED, "结束还原主程序成功"));
} else if (i != 238) {
a(new UpdateException(UpdateException.ERR_CODE_UPDATE_BOARD_FAILED, "主控结束升级失败"));
} else {
a(new UpdateException(UpdateException.ERR_CODE_UPDATE_BOARD_FAILED, "结束还原失败"));
}
}
}
private int b(byte[] bArr, int i) throws JimuException {
return a(new ProtocolPacket(38, a(bArr, i, i)));
}
private byte[] b(Firmware firmware) throws JimuException {
byte[] a;
if (firmware != null && (a = a(firmware.b(), firmware.a())) != null && a.length != 0) {
String a2 = FileHelper.a(firmware.b());
if (TextUtils.isEmpty(a2)) {
return null;
}
byte[] bytes = a2.replace(".bin", "").getBytes();
byte[] bArr = new byte[bytes.length + 5];
bArr[0] = (byte) (firmware.c() & 255);
bArr[1] = 0;
byte[] b = b(b(a));
bArr[2] = b[0];
bArr[3] = b[1];
bArr[4] = (byte) (bytes.length & 255);
System.arraycopy(bytes, 0, bArr, 5, bytes.length);
byte[] b2 = b(new ProtocolPacket(PeripheralType.SERVO, bArr));
if (b2 != null && b2.length >= 2 && firmware.c() == (b2[0] & 255) && (b2[1] & 255) == 0) {
return a;
}
}
return null;
}
private byte[] c(Firmware firmware) throws JimuException {
byte[] a;
if (firmware != null && (a = a(firmware.b(), firmware.a())) != null && a.length != 0) {
int length = a.length % 64;
if (length != 0) {
byte[] bArr = new byte[a.length + (64 - length)];
System.arraycopy(a, 0, bArr, 0, a.length);
a = bArr;
}
byte[] bArr2 = new byte[7];
bArr2[0] = 0;
System.arraycopy(b(b(a)), 0, bArr2, 1, 2);
System.arraycopy(a(a(a)), 0, bArr2, 3, 4);
if (a(new ProtocolPacket(35, bArr2)) == 0) {
return a;
}
}
return null;
}
public synchronized void a() {
if (!this.p && this.n != null) {
c(4);
a(this.m);
this.p = true;
}
}
private int c(byte[] bArr, int i, int i2) throws JimuException {
return a(new ProtocolPacket(36, a(bArr, i, i2)));
}
private byte[] b(int i, byte[] bArr, int i2, int i3) throws JimuException {
return b(new ProtocolPacket(129, a(i, bArr, i2, i3)));
}
/* JADX INFO: Access modifiers changed from: private */
public void c(int i) {
Handler handler = this.o;
if (handler == null) {
XLog.b("UpdateManager", "未知错误: mHandler==null");
d();
} else {
handler.sendEmptyMessage(i);
}
}
@Override // com.ubtrobot.jimu.connection.PacketsReceiveListener
public void a(String str, IPacket iPacket) {
if (iPacket == null) {
return;
}
try {
int f = iPacket.f() & 255;
if (f == 30) {
b(str, iPacket);
} else if (f == 31) {
c(str, iPacket);
} else if (f == 38) {
d(str, iPacket);
} else if (f == 131) {
e(str, iPacket);
}
} catch (Exception e) {
a(new UpdateException(-100, "升级失败", e));
}
}
private void b(BoardInfo boardInfo) {
this.c.b(this);
if (boardInfo != null) {
this.l.g(boardInfo);
return;
}
try {
try {
b(3000L);
this.d.g();
b(20L);
BoardInfo e = this.d.e();
if (e == null) {
b(2000L);
e = this.d.e();
}
if (e == null) {
a(new UpdateException(-100, "升级完成,但是读取主板信息失败"));
} else {
this.r = e;
this.l.g(e);
}
} catch (Exception e2) {
e2.printStackTrace();
}
d();
Timer timer = this.a;
if (timer != null) {
timer.cancel();
this.a = null;
}
} catch (Throwable th) {
d();
throw th;
}
}
@Override // com.ubtrobot.jimu.bluetooth.ConnectCallback
public void a(int i, String str) {
this.q++;
if (this.q > 3) {
a(new UpdateException(-99, "新主控升级失败重连3次失败"));
return;
}
Handler handler = this.o;
if (handler != null) {
handler.sendMessageDelayed(handler.obtainMessage(6), 3000L);
} else {
a(new UpdateException(-99, "新主控升级失败,重连失败"));
}
}
/* JADX INFO: Access modifiers changed from: private */
public void a(boolean z) {
boolean z2;
if (this.m == 2) {
if (z) {
try {
b(3000L);
this.d.g();
b(20L);
BoardInfo e = this.d.e();
if (e == null) {
b(2000L);
e = this.d.e();
}
if (e != null && !TextUtils.isEmpty(e.j()) && e.j().equals(this.j.d())) {
this.r = e;
a(PeripheralType.SERVO, e);
}
a(new UpdateException(UpdateException.ERR_CODE_UPDATE_SERVO_FAILED, "舵机升级完成,但是读取主板信息失败"));
return;
} catch (Exception e2) {
e2.printStackTrace();
}
}
if (this.h == null || this.h.size() == 0) {
b(this.r);
return;
}
}
Firmware poll = this.h.poll();
if (poll == null) {
b((BoardInfo) null);
return;
}
Log.d("UpdateManager", "升级传感器:" + poll.c());
this.m = 3;
this.k = poll;
try {
b(20L);
if (this.p) {
return;
}
byte[] b = b(poll);
if (b != null && b.length != 0) {
int b2 = b(b);
int i = 0;
int i2 = 0;
while (i < b2 - 1) {
b(20L);
if (!this.p) {
int i3 = i + 1;
byte[] b3 = b(poll.c(), b, b2, i3);
if (poll.c() == (b3[0] & 255) && (b3[1] & 255) == 0) {
int i4 = (i * 100) / b2;
if (i2 != i4) {
a(poll.c(), i4);
i2 = i4;
}
i = i3;
}
z2 = true;
break;
}
return;
}
z2 = false;
if (z2) {
a(new UpdateException(UpdateException.ERR_CODE_UPDATE_SENSOR_FAILED, "传感器升级失败81指令调用失败"));
return;
}
b(20L);
if (this.p) {
return;
}
if ((a(poll.c(), b, b2)[1] & 255) != 0) {
a(new UpdateException(UpdateException.ERR_CODE_UPDATE_SENSOR_FAILED, "传感器升级失败83指令调用失败"));
}
this.c.a(false);
return;
}
a(new UpdateException(UpdateException.ERR_CODE_UPDATE_SENSOR_FAILED, "传感器升级失败80指令调用失败"));
} catch (Exception e3) {
e3.printStackTrace();
a(new UpdateException(UpdateException.ERR_CODE_UPDATE_SENSOR_FAILED, "传感器升级失败", e3));
}
}
private byte[] b(ProtocolPacket protocolPacket) throws JimuException {
try {
byte[] g = this.c.a(protocolPacket).g();
if (g != null && g.length != 0) {
return g;
}
throw new JimuException(-21, "指令操作失败:" + Integer.toHexString(protocolPacket.f()));
} catch (RequestException e) {
e.printStackTrace();
throw new JimuException(e.getCode(), e.getMessage());
}
}
private void b(long j) {
try {
Thread.sleep(j);
} catch (Exception e) {
e.printStackTrace();
}
}
private int b(byte[] bArr) {
int length = bArr.length;
int i = length / 100;
return length % 100 > 0 ? i + 1 : i;
}
private byte[] a(Firmware firmware) throws JimuException {
byte[] a = a(firmware.b(), firmware.a());
if (a == null) {
return null;
}
String a2 = FileHelper.a(firmware.b());
if (TextUtils.isEmpty(a2)) {
return null;
}
byte[] bytes = a2.getBytes();
byte[] bArr = new byte[bytes.length + 1 + 2];
bArr[0] = (byte) (bytes.length & 255);
System.arraycopy(bytes, 0, bArr, 1, bytes.length);
System.arraycopy(b(b(a)), 0, bArr, bytes.length + 1, 2);
int a3 = a(new ProtocolPacket(26, bArr));
if (a3 == 0) {
return a;
}
XLog.b("UpdateManager", "cmd 1A failed:" + a3);
return null;
}
private int a(byte[] bArr, int i) throws JimuException {
return a(new ProtocolPacket(27, a(bArr, i, i)));
}
private byte[] a(int i, byte[] bArr, int i2) throws JimuException {
return b(new ProtocolPacket(131, a(i, bArr, i2, i2)));
}
/* JADX WARN: Removed duplicated region for block: B:14:0x0020 A[Catch: all -> 0x0068, TryCatch #0 {, blocks: (B:4:0x0003, B:12:0x001b, B:14:0x0020, B:15:0x0028, B:18:0x003a, B:19:0x0066, B:25:0x0063), top: B:3:0x0003, inners: #1 }] */
/*
Code decompiled incorrectly, please refer to instructions dump.
To view partially-correct code enable 'Show inconsistent code' option in preferences
*/
private void a(final int r9, int r10) {
/*
r8 = this;
monitor-enter(r8)
int r10 = r10 * 9
int r10 = r10 / 10
r8.b = r10 // Catch: java.lang.Throwable -> L68
int r10 = r8.b // Catch: java.lang.Throwable -> L68
r0 = 90
if (r10 != r0) goto L3a
r10 = 113(0x71, float:1.58E-43)
if (r10 == r9) goto L19
r10 = 112(0x70, float:1.57E-43)
if (r10 != r9) goto L16
goto L19
L16:
r0 = 1000(0x3e8, double:4.94E-321)
goto L1b
L19:
r0 = 7000(0x1b58, double:3.4585E-320)
L1b:
r6 = r0
java.util.Timer r10 = r8.a // Catch: java.lang.Throwable -> L68
if (r10 == 0) goto L28
java.util.Timer r10 = r8.a // Catch: java.lang.Throwable -> L68
r10.cancel() // Catch: java.lang.Throwable -> L68
r10 = 0
r8.a = r10 // Catch: java.lang.Throwable -> L68
L28:
java.util.Timer r10 = new java.util.Timer // Catch: java.lang.Throwable -> L68
r10.<init>() // Catch: java.lang.Throwable -> L68
r8.a = r10 // Catch: java.lang.Throwable -> L68
java.util.Timer r2 = r8.a // Catch: java.lang.Throwable -> L68
com.ubtrobot.jimu.robotapi.UpdateManager$3 r3 = new com.ubtrobot.jimu.robotapi.UpdateManager$3 // Catch: java.lang.Throwable -> L68
r3.<init>() // Catch: java.lang.Throwable -> L68
r4 = r6
r2.scheduleAtFixedRate(r3, r4, r6) // Catch: java.lang.Throwable -> L68
L3a:
com.ubtrobot.jimu.robotapi.UpdateManager$UpdateProgressListener r10 = r8.l // Catch: java.lang.Exception -> L62 java.lang.Throwable -> L68
int r0 = r8.b // Catch: java.lang.Exception -> L62 java.lang.Throwable -> L68
r10.a(r9, r0) // Catch: java.lang.Exception -> L62 java.lang.Throwable -> L68
java.lang.String r10 = "UpdateManager"
java.lang.StringBuilder r0 = new java.lang.StringBuilder // Catch: java.lang.Exception -> L62 java.lang.Throwable -> L68
r0.<init>() // Catch: java.lang.Exception -> L62 java.lang.Throwable -> L68
java.lang.String r1 = "updateProgress type:"
r0.append(r1) // Catch: java.lang.Exception -> L62 java.lang.Throwable -> L68
r0.append(r9) // Catch: java.lang.Exception -> L62 java.lang.Throwable -> L68
java.lang.String r9 = " progress:"
r0.append(r9) // Catch: java.lang.Exception -> L62 java.lang.Throwable -> L68
int r9 = r8.b // Catch: java.lang.Exception -> L62 java.lang.Throwable -> L68
r0.append(r9) // Catch: java.lang.Exception -> L62 java.lang.Throwable -> L68
java.lang.String r9 = r0.toString() // Catch: java.lang.Exception -> L62 java.lang.Throwable -> L68
android.util.Log.d(r10, r9) // Catch: java.lang.Exception -> L62 java.lang.Throwable -> L68
goto L66
L62:
r9 = move-exception
r9.printStackTrace() // Catch: java.lang.Throwable -> L68
L66:
monitor-exit(r8) // Catch: java.lang.Throwable -> L68
return
L68:
r9 = move-exception
monitor-exit(r8) // Catch: java.lang.Throwable -> L68
throw r9
*/
throw new UnsupportedOperationException("Method not decompiled: com.ubtrobot.jimu.robotapi.UpdateManager.a(int, int):void");
}
private void a(int i, Object obj) {
try {
this.l.a(i, obj);
} catch (Exception e) {
e.printStackTrace();
}
}
/* JADX INFO: Access modifiers changed from: private */
public void a(UpdateException updateException) {
try {
this.l.a(updateException);
this.c.b(this);
} catch (Exception e) {
e.printStackTrace();
}
try {
Log.e("UpdateManager", "updateFailed:" + updateException.getMessage());
c(4);
} catch (Exception e2) {
e2.printStackTrace();
d();
}
Timer timer = this.a;
if (timer != null) {
timer.cancel();
this.a = null;
}
}
private void a(int i) {
try {
this.l.a(i);
} catch (Exception e) {
e.printStackTrace();
}
}
private int a(ProtocolPacket protocolPacket) throws JimuException {
return b(protocolPacket)[0] & 255;
}
private byte[] a(byte[] bArr, int i, int i2) {
int i3 = (i2 - 1) * 100;
int length = (i2 == i ? bArr.length : i2 * 100) - i3;
byte[] bArr2 = new byte[length + 2];
System.arraycopy(b(i2), 0, bArr2, 0, 2);
System.arraycopy(bArr, i3, bArr2, 2, length);
return bArr2;
}
private byte[] a(int i, byte[] bArr, int i2, int i3) {
int i4 = (i3 - 1) * 100;
int length = (i3 == i2 ? bArr.length : i3 * 100) - i4;
byte[] bArr2 = new byte[length + 3];
bArr2[0] = (byte) (i & 255);
System.arraycopy(b(i3), 0, bArr2, 1, 2);
System.arraycopy(bArr, i4, bArr2, 3, length);
return bArr2;
}
private byte[] a(String str, String str2) {
File file = new File(str);
if (file.exists() && FileHelper.a(str2, str)) {
return FileHelper.b(file);
}
return null;
}
private long a(byte[] bArr) {
long[] jArr = new long[DataDecryptTool.DECRYPT_ALL_FILE];
for (long j = 0; j < 256; j++) {
long j2 = j;
for (long j3 = 0; j3 < 8; j3++) {
j2 = (j2 & 1) == 1 ? (j2 >> 1) ^ 3988292384L : j2 >> 1;
}
jArr[(int) j] = j2;
}
long j4 = 4294967295L;
for (byte b : bArr) {
j4 = (j4 >> 8) ^ jArr[(int) ((b ^ j4) & 255)];
}
return j4;
}
}

View File

@@ -0,0 +1,71 @@
package com.ubtrobot.log;
import android.content.Context;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.CsvFormatStrategy;
import com.orhanobut.logger.DiskLogAdapter;
import com.orhanobut.logger.LogAdapter;
import com.orhanobut.logger.LogcatLogStrategy;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.PrettyFormatStrategy;
import com.orhanobut.logger.Printer;
import java.io.File;
import java.lang.Thread;
import java.text.SimpleDateFormat;
import java.util.Locale;
/* loaded from: classes2.dex */
public class ALog {
private static AndroidLogAdapter a;
private static Thread.UncaughtExceptionHandler b;
public static void a(Context context, String str) {
PrettyFormatStrategy.Builder a2 = PrettyFormatStrategy.a();
a2.a(false);
a2.a(0);
a2.b(1);
a2.a(new LogcatLogStrategy());
a2.a(str);
a = new AndroidLogAdapter(a2.a());
Logger.a((LogAdapter) a);
File a3 = ExternalOverFroyoUtils.a(context, "log");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd HH:mm:ss.SSS", Locale.UK);
CsvFormatStrategy.Builder a4 = CsvFormatStrategy.a();
a4.a(simpleDateFormat);
a4.a(a3.getAbsolutePath());
a4.b(str);
Logger.a((LogAdapter) new DiskLogAdapter(a4.a()));
Thread.setDefaultUncaughtExceptionHandler(a(context));
}
public static void b(String str, Object... objArr) {
Logger.b(str, objArr);
}
public static void c(String str, Object... objArr) {
Logger.c(str, objArr);
}
public static Printer a(String str) {
return Logger.a(str);
}
public static void a(Object obj) {
Logger.a(obj);
}
public static void a(String str, Object... objArr) {
Logger.a(str, objArr);
}
public static void a(Throwable th, String str, Object... objArr) {
Logger.a(th, str, objArr);
}
private static Thread.UncaughtExceptionHandler a(Context context) {
if (b == null) {
b = CrashExceptionHandler.b(context);
}
return b;
}
}

View File

@@ -0,0 +1,14 @@
package com.ubtrobot.log;
import android.os.Build;
/* loaded from: classes2.dex */
class AndroidVersionCheckUtils {
public static boolean a() {
return Build.VERSION.SDK_INT >= 8;
}
public static boolean b() {
return Build.VERSION.SDK_INT >= 9;
}
}

View File

@@ -0,0 +1,184 @@
package com.ubtrobot.log;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Process;
import android.util.Log;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.Thread;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/* loaded from: classes2.dex */
public class CrashExceptionHandler implements Thread.UncaughtExceptionHandler {
private static CrashExceptionHandler d;
private Context a;
private Thread.UncaughtExceptionHandler b;
private Map<String, String> c = new HashMap();
private CrashExceptionHandler(Context context) {
c(context);
}
private boolean a(Throwable th, Thread thread) {
if (th == null) {
return true;
}
a(this.a);
a(th);
return true;
}
public static CrashExceptionHandler b(Context context) {
if (d == null) {
d = new CrashExceptionHandler(context);
}
return d;
}
private void c(Context context) {
this.a = context;
this.b = Thread.getDefaultUncaughtExceptionHandler();
}
@Override // java.lang.Thread.UncaughtExceptionHandler
public void uncaughtException(Thread thread, Throwable th) {
Thread.UncaughtExceptionHandler uncaughtExceptionHandler;
if (!a(th, thread) || (uncaughtExceptionHandler = this.b) == null) {
this.b.uncaughtException(thread, th);
return;
}
uncaughtExceptionHandler.uncaughtException(thread, th);
Process.killProcess(Process.myPid());
System.exit(10);
}
@SuppressLint({"SimpleDateFormat"})
private void a(Throwable th) {
StringBuilder sb;
if (th == null) {
return;
}
StringBuilder sb2 = new StringBuilder();
for (String str : this.c.keySet()) {
String str2 = this.c.get(str);
sb2.append(str);
sb2.append("=");
sb2.append(str2);
sb2.append("\n");
}
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
th.printStackTrace(printWriter);
for (Throwable cause = th.getCause(); cause != null; cause = cause.getCause()) {
cause.printStackTrace(printWriter);
}
printWriter.close();
sb2.append(stringWriter.toString());
FileOutputStream fileOutputStream = null;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
long currentTimeMillis = System.currentTimeMillis();
String str3 = simpleDateFormat.format(new Date()) + "_" + currentTimeMillis + ".txt";
try {
try {
File a = ExternalOverFroyoUtils.a(this.a, "crash");
if (!a.exists()) {
a.mkdirs();
}
FileOutputStream fileOutputStream2 = new FileOutputStream(new File(a.getAbsolutePath() + File.separator + str3));
try {
fileOutputStream2.write(sb2.toString().getBytes());
try {
fileOutputStream2.close();
} catch (IOException e) {
e = e;
sb = new StringBuilder();
sb.append("关闭Crash文件流时出错:");
sb.append(e.getMessage());
Log.e("CrashExceptionHandler", sb.toString());
}
} catch (FileNotFoundException e2) {
e = e2;
fileOutputStream = fileOutputStream2;
Log.e("CrashExceptionHandler", "保存crash文件时出错" + e.getMessage());
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e3) {
e = e3;
sb = new StringBuilder();
sb.append("关闭Crash文件流时出错:");
sb.append(e.getMessage());
Log.e("CrashExceptionHandler", sb.toString());
}
}
} catch (Exception e4) {
e = e4;
fileOutputStream = fileOutputStream2;
Log.e("CrashExceptionHandler", "保存crash文件时出错" + e.getMessage());
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e5) {
e = e5;
sb = new StringBuilder();
sb.append("关闭Crash文件流时出错:");
sb.append(e.getMessage());
Log.e("CrashExceptionHandler", sb.toString());
}
}
} catch (Throwable th2) {
th = th2;
fileOutputStream = fileOutputStream2;
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e6) {
Log.e("CrashExceptionHandler", "关闭Crash文件流时出错:" + e6.getMessage());
}
}
throw th;
}
} catch (FileNotFoundException e7) {
e = e7;
} catch (Exception e8) {
e = e8;
}
} catch (Throwable th3) {
th = th3;
}
}
private void a(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 1);
if (packageInfo != null) {
String str = packageInfo.versionName == null ? "null" : packageInfo.versionName;
String str2 = packageInfo.versionCode + "";
this.c.put("versionName", str);
this.c.put("versionCode", str2);
}
} catch (PackageManager.NameNotFoundException unused) {
Log.e("CrashExceptionHandler", "收集包信息时出错。");
}
try {
for (Field field : Build.class.getDeclaredFields()) {
field.setAccessible(true);
this.c.put(field.getName(), field.get(null).toString());
}
} catch (Exception unused2) {
Log.e("CrashExceptionHandler", "收集crash信息时出错。");
}
}
}

View File

@@ -0,0 +1,55 @@
package com.ubtrobot.log;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import java.io.File;
@TargetApi(9)
/* loaded from: classes2.dex */
public class ExternalOverFroyoUtils {
public enum Dir {
Model("model"),
Cache("cache"),
User("user"),
Image("image");
private String name;
Dir(String str) {
this.name = str;
}
public String getName() {
return this.name;
}
}
public static boolean a() {
if (AndroidVersionCheckUtils.b()) {
return Environment.isExternalStorageRemovable();
}
return true;
}
public static File a(Context context, String str) {
String path = context.getCacheDir().getPath();
try {
if ("mounted".equals(Environment.getExternalStorageState()) || !a()) {
path = a(context).getPath();
}
} catch (Exception e) {
Log.e("DiskCacheDir", e.getMessage() + "");
}
return new File(path + File.separator + str);
}
public static File a(Context context) {
if (AndroidVersionCheckUtils.a()) {
return context.getExternalCacheDir();
}
return new File(Environment.getExternalStorageDirectory().getPath() + ("/Android/data/" + context.getPackageName() + "/cache/"));
}
}

View File

@@ -0,0 +1,38 @@
package com.ubtrobot.okhttp.interceptor.sign;
import com.ubt.jimu.base.http.ApiConstants;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
/* loaded from: classes2.dex */
public class AuthorizationInterceptor implements Interceptor {
private final AuthenticationInfoSource a;
public interface AuthenticationInfoSource {
String a(Request request);
String b(Request request);
}
public AuthorizationInterceptor(AuthenticationInfoSource authenticationInfoSource) {
if (authenticationInfoSource == null) {
throw new IllegalArgumentException("Argument infoSource is null.");
}
this.a = authenticationInfoSource;
}
@Override // okhttp3.Interceptor
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
Request.Builder newBuilder = request.newBuilder();
if (this.a.b(request) != null) {
newBuilder.header("Authorization", this.a.b(request));
}
if (this.a.a(request) != null) {
newBuilder.header(ApiConstants.KEY_DEVICE_ID, this.a.a(request));
}
return chain.proceed(newBuilder.build());
}
}

View File

@@ -0,0 +1,99 @@
package com.ubtrobot.okhttp.interceptor.sign;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import com.ubt.jimu.base.http.ApiConstants;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.json.JSONException;
import org.json.JSONObject;
/* loaded from: classes2.dex */
public class HttpSignInterceptor implements Interceptor {
private final String a;
private final DeviceInfoSource b;
private final URestSigner c;
private volatile boolean d;
private volatile Pair<Long, Long> e;
private OkHttpClient f;
public interface DeviceInfoSource {
String a(Request request);
}
public HttpSignInterceptor(String str, String str2, DeviceInfoSource deviceInfoSource) {
if (str == null || str.length() <= 0 || str2 == null || str2.length() <= 0) {
throw new IllegalArgumentException("appId or appKey arguments is empty.");
}
if (deviceInfoSource == null) {
throw new IllegalArgumentException("Argument deviceInfoSource is null.");
}
this.a = str;
this.c = new URestSigner(str2);
this.b = deviceInfoSource;
}
private long a() throws IOException {
if (this.f == null) {
this.f = new OkHttpClient();
}
ResponseBody body = this.f.newCall(new Request.Builder().url("https://apis.ubtrobot.com/v1/client-auth-service/api/timestamp").get().build()).execute().body();
if (body == null) {
throw new IOException("Service response empty body.");
}
try {
return new JSONObject(new String(body.bytes())).getLong("timestamp");
} catch (JSONException e) {
throw new IOException("Service response unexpected json object.", e);
}
}
private long b() {
return this.d ? ((Long) this.e.second).longValue() + TimeUnit.MILLISECONDS.toSeconds(SystemClock.elapsedRealtime() - ((Long) this.e.first).longValue()) : System.currentTimeMillis() / 1000;
}
private void c() {
if (this.d) {
return;
}
synchronized (this) {
if (this.d) {
return;
}
try {
this.e = new Pair<>(Long.valueOf(SystemClock.elapsedRealtime()), Long.valueOf(a() + TimeUnit.MILLISECONDS.toSeconds((SystemClock.elapsedRealtime() - SystemClock.elapsedRealtime()) / 2)));
this.d = true;
this.f = null;
} catch (IOException e) {
Log.e("HttpSignInterceptor", "Sync time failed before request which need sign.", e);
}
}
}
@Override // okhttp3.Interceptor
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
String a = this.b.a(request);
if (TextUtils.isEmpty(a)) {
throw new IllegalStateException("DeviceInfoSource.getDeviceId return an empty device id.");
}
String header = request.header(ApiConstants.KEY_DEVICE_ID);
if (header != null && !a.equals(header)) {
throw new IllegalStateException("X-UBT-DeviceId header value is different from " + a);
}
String header2 = request.header(ApiConstants.KEY_APP_ID);
if (header2 == null || this.a.equals(header2)) {
c();
return chain.proceed(request.newBuilder().header(ApiConstants.KEY_APP_ID, this.a).header(ApiConstants.KEY_DEVICE_ID, a).header(ApiConstants.KEY_SIGN, this.c.a(a, b(), UUID.randomUUID().toString().substring(0, 8))).build());
}
throw new IllegalStateException("X-UBT-AppId header value is different from " + this.a);
}
}

View File

@@ -0,0 +1,30 @@
package com.ubtrobot.okhttp.interceptor.sign;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/* loaded from: classes2.dex */
public class URestSigner {
private final String a;
public URestSigner(String str) {
this.a = str;
}
public String a(String str, long j, String str2) {
return a(j + this.a + str2 + str) + " " + j + " " + str2 + " v2";
}
private String a(String str) {
try {
String bigInteger = new BigInteger(1, MessageDigest.getInstance("MD5").digest(str.getBytes())).toString(16);
while (bigInteger.length() < 32) {
bigInteger = "0" + bigInteger;
}
return bigInteger;
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
}

Some files were not shown because too many files have changed in this diff Show More