Commit 66d91c45 by Wyh

7.24 修改打印邏輯

parent 2fd4d7af
...@@ -44,7 +44,7 @@ android { ...@@ -44,7 +44,7 @@ android {
/** /**
* 版本号 * 版本号
*/ */
schemaVersion 9 schemaVersion 10
/** /**
* greendao输出dao的数据库操作实体类文件夹(相对路径 包名+自定义路径名称,包将创建于包名的直接路径下) * greendao输出dao的数据库操作实体类文件夹(相对路径 包名+自定义路径名称,包将创建于包名的直接路径下)
*/ */
......
...@@ -36,6 +36,8 @@ public class PrinterDeviceBean implements Serializable { ...@@ -36,6 +36,8 @@ public class PrinterDeviceBean implements Serializable {
private String noteContent;//備註 private String noteContent;//備註
private Long printerDeviceDefaultId; private Long printerDeviceDefaultId;
private int printerDeviceType;//打印機類型 1:網絡打印 2:本地打印(N5,Sunmi手持打印) 3:USB打印 4:藍牙打印
/** /**
* 飛單1打印機id * 飛單1打印機id
*/ */
...@@ -45,19 +47,19 @@ public class PrinterDeviceBean implements Serializable { ...@@ -45,19 +47,19 @@ public class PrinterDeviceBean implements Serializable {
*/ */
private Long flyPrinterDeviceId2; private Long flyPrinterDeviceId2;
private int foodIsBold;//食品是否加粗 1是 2否 private int foodIsBold;//食品是否加粗 0預設 1是 2否
private String foodFont; private String foodFont;//食品字體大小 0預設
private int foodIsItalic;//食品是否斜體 1是 2否 private int foodIsItalic;//食品是否斜體 0預設 1是 2否
private int modifierIsBold;//細項是否加粗 1是 2否 private int modifierIsBold;//細項是否加粗 0預設 1是 2否
private String modifierFont;//細項字號 private String modifierFont;//細項字號 0預設
private int modifierIsItalic;//細項是否斜體 1是 2否 private int modifierIsItalic;//細項是否斜體 0預設 1是 2否
private int numberIsFlip;//數量大於1顔色是否翻轉 1是 2否 private int numberIsFlip;//數量大於1顔色是否翻轉 0預設 1是 2否
@Generated(hash = 626885316) @Generated(hash = 626885316)
...@@ -70,9 +72,8 @@ public class PrinterDeviceBean implements Serializable { ...@@ -70,9 +72,8 @@ public class PrinterDeviceBean implements Serializable {
this.paperSpecification = paperSpecification; this.paperSpecification = paperSpecification;
} }
@Generated(hash = 1637885194) @Generated(hash = 23385471)
public PrinterDeviceBean(Long id, Long dbid, String name, Integer restaurantId, String ip, Long uid, Integer port, Integer type, Long printerModelId, String paperSpecification, int lineFontStop, String printerName, String model, String noteContent, Long printerDeviceDefaultId, Long flyPrinterDeviceId, Long flyPrinterDeviceId2, int foodIsBold, String foodFont, int foodIsItalic, int modifierIsBold, String modifierFont, int modifierIsItalic, public PrinterDeviceBean(Long id, Long dbid, String name, Integer restaurantId, String ip, Long uid, Integer port, Integer type, Long printerModelId, String paperSpecification, int lineFontStop, String printerName, String model, String noteContent, Long printerDeviceDefaultId, int printerDeviceType, Long flyPrinterDeviceId, Long flyPrinterDeviceId2, int foodIsBold, String foodFont, int foodIsItalic, int modifierIsBold, String modifierFont, int modifierIsItalic, int numberIsFlip) {
int numberIsFlip) {
this.id = id; this.id = id;
this.dbid = dbid; this.dbid = dbid;
this.name = name; this.name = name;
...@@ -88,6 +89,7 @@ public class PrinterDeviceBean implements Serializable { ...@@ -88,6 +89,7 @@ public class PrinterDeviceBean implements Serializable {
this.model = model; this.model = model;
this.noteContent = noteContent; this.noteContent = noteContent;
this.printerDeviceDefaultId = printerDeviceDefaultId; this.printerDeviceDefaultId = printerDeviceDefaultId;
this.printerDeviceType = printerDeviceType;
this.flyPrinterDeviceId = flyPrinterDeviceId; this.flyPrinterDeviceId = flyPrinterDeviceId;
this.flyPrinterDeviceId2 = flyPrinterDeviceId2; this.flyPrinterDeviceId2 = flyPrinterDeviceId2;
this.foodIsBold = foodIsBold; this.foodIsBold = foodIsBold;
...@@ -297,4 +299,14 @@ public class PrinterDeviceBean implements Serializable { ...@@ -297,4 +299,14 @@ public class PrinterDeviceBean implements Serializable {
public void setLineFontStop(int lineFontStop) { public void setLineFontStop(int lineFontStop) {
this.lineFontStop = lineFontStop; this.lineFontStop = lineFontStop;
} }
public int getPrinterDeviceType() {
return printerDeviceType;
}
public void setPrinterDeviceType(int printerDeviceType) {
this.printerDeviceType = printerDeviceType;
}
} }
...@@ -14,10 +14,10 @@ import org.greenrobot.greendao.identityscope.IdentityScopeType; ...@@ -14,10 +14,10 @@ import org.greenrobot.greendao.identityscope.IdentityScopeType;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/** /**
* Master of DAO (schema version 9): knows all DAOs. * Master of DAO (schema version 10): knows all DAOs.
*/ */
public class DaoMaster extends AbstractDaoMaster { public class DaoMaster extends AbstractDaoMaster {
public static final int SCHEMA_VERSION = 9; public static final int SCHEMA_VERSION = 10;
/** Creates underlying database table using DAOs. */ /** Creates underlying database table using DAOs. */
public static void createAllTables(Database db, boolean ifNotExists) { public static void createAllTables(Database db, boolean ifNotExists) {
......
...@@ -39,15 +39,16 @@ public class PrinterDeviceBeanDao extends AbstractDao<PrinterDeviceBean, Long> { ...@@ -39,15 +39,16 @@ public class PrinterDeviceBeanDao extends AbstractDao<PrinterDeviceBean, Long> {
public final static Property Model = new Property(12, String.class, "model", false, "MODEL"); public final static Property Model = new Property(12, String.class, "model", false, "MODEL");
public final static Property NoteContent = new Property(13, String.class, "noteContent", false, "NOTE_CONTENT"); public final static Property NoteContent = new Property(13, String.class, "noteContent", false, "NOTE_CONTENT");
public final static Property PrinterDeviceDefaultId = new Property(14, Long.class, "printerDeviceDefaultId", false, "PRINTER_DEVICE_DEFAULT_ID"); public final static Property PrinterDeviceDefaultId = new Property(14, Long.class, "printerDeviceDefaultId", false, "PRINTER_DEVICE_DEFAULT_ID");
public final static Property FlyPrinterDeviceId = new Property(15, Long.class, "flyPrinterDeviceId", false, "FLY_PRINTER_DEVICE_ID"); public final static Property PrinterDeviceType = new Property(15, int.class, "printerDeviceType", false, "PRINTER_DEVICE_TYPE");
public final static Property FlyPrinterDeviceId2 = new Property(16, Long.class, "flyPrinterDeviceId2", false, "FLY_PRINTER_DEVICE_ID2"); public final static Property FlyPrinterDeviceId = new Property(16, Long.class, "flyPrinterDeviceId", false, "FLY_PRINTER_DEVICE_ID");
public final static Property FoodIsBold = new Property(17, int.class, "foodIsBold", false, "FOOD_IS_BOLD"); public final static Property FlyPrinterDeviceId2 = new Property(17, Long.class, "flyPrinterDeviceId2", false, "FLY_PRINTER_DEVICE_ID2");
public final static Property FoodFont = new Property(18, String.class, "foodFont", false, "FOOD_FONT"); public final static Property FoodIsBold = new Property(18, int.class, "foodIsBold", false, "FOOD_IS_BOLD");
public final static Property FoodIsItalic = new Property(19, int.class, "foodIsItalic", false, "FOOD_IS_ITALIC"); public final static Property FoodFont = new Property(19, String.class, "foodFont", false, "FOOD_FONT");
public final static Property ModifierIsBold = new Property(20, int.class, "modifierIsBold", false, "MODIFIER_IS_BOLD"); public final static Property FoodIsItalic = new Property(20, int.class, "foodIsItalic", false, "FOOD_IS_ITALIC");
public final static Property ModifierFont = new Property(21, String.class, "modifierFont", false, "MODIFIER_FONT"); public final static Property ModifierIsBold = new Property(21, int.class, "modifierIsBold", false, "MODIFIER_IS_BOLD");
public final static Property ModifierIsItalic = new Property(22, int.class, "modifierIsItalic", false, "MODIFIER_IS_ITALIC"); public final static Property ModifierFont = new Property(22, String.class, "modifierFont", false, "MODIFIER_FONT");
public final static Property NumberIsFlip = new Property(23, int.class, "numberIsFlip", false, "NUMBER_IS_FLIP"); public final static Property ModifierIsItalic = new Property(23, int.class, "modifierIsItalic", false, "MODIFIER_IS_ITALIC");
public final static Property NumberIsFlip = new Property(24, int.class, "numberIsFlip", false, "NUMBER_IS_FLIP");
} }
...@@ -78,15 +79,16 @@ public class PrinterDeviceBeanDao extends AbstractDao<PrinterDeviceBean, Long> { ...@@ -78,15 +79,16 @@ public class PrinterDeviceBeanDao extends AbstractDao<PrinterDeviceBean, Long> {
"\"MODEL\" TEXT," + // 12: model "\"MODEL\" TEXT," + // 12: model
"\"NOTE_CONTENT\" TEXT," + // 13: noteContent "\"NOTE_CONTENT\" TEXT," + // 13: noteContent
"\"PRINTER_DEVICE_DEFAULT_ID\" INTEGER," + // 14: printerDeviceDefaultId "\"PRINTER_DEVICE_DEFAULT_ID\" INTEGER," + // 14: printerDeviceDefaultId
"\"FLY_PRINTER_DEVICE_ID\" INTEGER," + // 15: flyPrinterDeviceId "\"PRINTER_DEVICE_TYPE\" INTEGER NOT NULL ," + // 15: printerDeviceType
"\"FLY_PRINTER_DEVICE_ID2\" INTEGER," + // 16: flyPrinterDeviceId2 "\"FLY_PRINTER_DEVICE_ID\" INTEGER," + // 16: flyPrinterDeviceId
"\"FOOD_IS_BOLD\" INTEGER NOT NULL ," + // 17: foodIsBold "\"FLY_PRINTER_DEVICE_ID2\" INTEGER," + // 17: flyPrinterDeviceId2
"\"FOOD_FONT\" TEXT," + // 18: foodFont "\"FOOD_IS_BOLD\" INTEGER NOT NULL ," + // 18: foodIsBold
"\"FOOD_IS_ITALIC\" INTEGER NOT NULL ," + // 19: foodIsItalic "\"FOOD_FONT\" TEXT," + // 19: foodFont
"\"MODIFIER_IS_BOLD\" INTEGER NOT NULL ," + // 20: modifierIsBold "\"FOOD_IS_ITALIC\" INTEGER NOT NULL ," + // 20: foodIsItalic
"\"MODIFIER_FONT\" TEXT," + // 21: modifierFont "\"MODIFIER_IS_BOLD\" INTEGER NOT NULL ," + // 21: modifierIsBold
"\"MODIFIER_IS_ITALIC\" INTEGER NOT NULL ," + // 22: modifierIsItalic "\"MODIFIER_FONT\" TEXT," + // 22: modifierFont
"\"NUMBER_IS_FLIP\" INTEGER NOT NULL );"); // 23: numberIsFlip "\"MODIFIER_IS_ITALIC\" INTEGER NOT NULL ," + // 23: modifierIsItalic
"\"NUMBER_IS_FLIP\" INTEGER NOT NULL );"); // 24: numberIsFlip
} }
/** Drops the underlying database table. */ /** Drops the underlying database table. */
...@@ -169,31 +171,32 @@ public class PrinterDeviceBeanDao extends AbstractDao<PrinterDeviceBean, Long> { ...@@ -169,31 +171,32 @@ public class PrinterDeviceBeanDao extends AbstractDao<PrinterDeviceBean, Long> {
if (printerDeviceDefaultId != null) { if (printerDeviceDefaultId != null) {
stmt.bindLong(15, printerDeviceDefaultId); stmt.bindLong(15, printerDeviceDefaultId);
} }
stmt.bindLong(16, entity.getPrinterDeviceType());
Long flyPrinterDeviceId = entity.getFlyPrinterDeviceId(); Long flyPrinterDeviceId = entity.getFlyPrinterDeviceId();
if (flyPrinterDeviceId != null) { if (flyPrinterDeviceId != null) {
stmt.bindLong(16, flyPrinterDeviceId); stmt.bindLong(17, flyPrinterDeviceId);
} }
Long flyPrinterDeviceId2 = entity.getFlyPrinterDeviceId2(); Long flyPrinterDeviceId2 = entity.getFlyPrinterDeviceId2();
if (flyPrinterDeviceId2 != null) { if (flyPrinterDeviceId2 != null) {
stmt.bindLong(17, flyPrinterDeviceId2); stmt.bindLong(18, flyPrinterDeviceId2);
} }
stmt.bindLong(18, entity.getFoodIsBold()); stmt.bindLong(19, entity.getFoodIsBold());
String foodFont = entity.getFoodFont(); String foodFont = entity.getFoodFont();
if (foodFont != null) { if (foodFont != null) {
stmt.bindString(19, foodFont); stmt.bindString(20, foodFont);
} }
stmt.bindLong(20, entity.getFoodIsItalic()); stmt.bindLong(21, entity.getFoodIsItalic());
stmt.bindLong(21, entity.getModifierIsBold()); stmt.bindLong(22, entity.getModifierIsBold());
String modifierFont = entity.getModifierFont(); String modifierFont = entity.getModifierFont();
if (modifierFont != null) { if (modifierFont != null) {
stmt.bindString(22, modifierFont); stmt.bindString(23, modifierFont);
} }
stmt.bindLong(23, entity.getModifierIsItalic()); stmt.bindLong(24, entity.getModifierIsItalic());
stmt.bindLong(24, entity.getNumberIsFlip()); stmt.bindLong(25, entity.getNumberIsFlip());
} }
@Override @Override
...@@ -270,31 +273,32 @@ public class PrinterDeviceBeanDao extends AbstractDao<PrinterDeviceBean, Long> { ...@@ -270,31 +273,32 @@ public class PrinterDeviceBeanDao extends AbstractDao<PrinterDeviceBean, Long> {
if (printerDeviceDefaultId != null) { if (printerDeviceDefaultId != null) {
stmt.bindLong(15, printerDeviceDefaultId); stmt.bindLong(15, printerDeviceDefaultId);
} }
stmt.bindLong(16, entity.getPrinterDeviceType());
Long flyPrinterDeviceId = entity.getFlyPrinterDeviceId(); Long flyPrinterDeviceId = entity.getFlyPrinterDeviceId();
if (flyPrinterDeviceId != null) { if (flyPrinterDeviceId != null) {
stmt.bindLong(16, flyPrinterDeviceId); stmt.bindLong(17, flyPrinterDeviceId);
} }
Long flyPrinterDeviceId2 = entity.getFlyPrinterDeviceId2(); Long flyPrinterDeviceId2 = entity.getFlyPrinterDeviceId2();
if (flyPrinterDeviceId2 != null) { if (flyPrinterDeviceId2 != null) {
stmt.bindLong(17, flyPrinterDeviceId2); stmt.bindLong(18, flyPrinterDeviceId2);
} }
stmt.bindLong(18, entity.getFoodIsBold()); stmt.bindLong(19, entity.getFoodIsBold());
String foodFont = entity.getFoodFont(); String foodFont = entity.getFoodFont();
if (foodFont != null) { if (foodFont != null) {
stmt.bindString(19, foodFont); stmt.bindString(20, foodFont);
} }
stmt.bindLong(20, entity.getFoodIsItalic()); stmt.bindLong(21, entity.getFoodIsItalic());
stmt.bindLong(21, entity.getModifierIsBold()); stmt.bindLong(22, entity.getModifierIsBold());
String modifierFont = entity.getModifierFont(); String modifierFont = entity.getModifierFont();
if (modifierFont != null) { if (modifierFont != null) {
stmt.bindString(22, modifierFont); stmt.bindString(23, modifierFont);
} }
stmt.bindLong(23, entity.getModifierIsItalic()); stmt.bindLong(24, entity.getModifierIsItalic());
stmt.bindLong(24, entity.getNumberIsFlip()); stmt.bindLong(25, entity.getNumberIsFlip());
} }
@Override @Override
...@@ -320,15 +324,16 @@ public class PrinterDeviceBeanDao extends AbstractDao<PrinterDeviceBean, Long> { ...@@ -320,15 +324,16 @@ public class PrinterDeviceBeanDao extends AbstractDao<PrinterDeviceBean, Long> {
cursor.isNull(offset + 12) ? null : cursor.getString(offset + 12), // model cursor.isNull(offset + 12) ? null : cursor.getString(offset + 12), // model
cursor.isNull(offset + 13) ? null : cursor.getString(offset + 13), // noteContent cursor.isNull(offset + 13) ? null : cursor.getString(offset + 13), // noteContent
cursor.isNull(offset + 14) ? null : cursor.getLong(offset + 14), // printerDeviceDefaultId cursor.isNull(offset + 14) ? null : cursor.getLong(offset + 14), // printerDeviceDefaultId
cursor.isNull(offset + 15) ? null : cursor.getLong(offset + 15), // flyPrinterDeviceId cursor.getInt(offset + 15), // printerDeviceType
cursor.isNull(offset + 16) ? null : cursor.getLong(offset + 16), // flyPrinterDeviceId2 cursor.isNull(offset + 16) ? null : cursor.getLong(offset + 16), // flyPrinterDeviceId
cursor.getInt(offset + 17), // foodIsBold cursor.isNull(offset + 17) ? null : cursor.getLong(offset + 17), // flyPrinterDeviceId2
cursor.isNull(offset + 18) ? null : cursor.getString(offset + 18), // foodFont cursor.getInt(offset + 18), // foodIsBold
cursor.getInt(offset + 19), // foodIsItalic cursor.isNull(offset + 19) ? null : cursor.getString(offset + 19), // foodFont
cursor.getInt(offset + 20), // modifierIsBold cursor.getInt(offset + 20), // foodIsItalic
cursor.isNull(offset + 21) ? null : cursor.getString(offset + 21), // modifierFont cursor.getInt(offset + 21), // modifierIsBold
cursor.getInt(offset + 22), // modifierIsItalic cursor.isNull(offset + 22) ? null : cursor.getString(offset + 22), // modifierFont
cursor.getInt(offset + 23) // numberIsFlip cursor.getInt(offset + 23), // modifierIsItalic
cursor.getInt(offset + 24) // numberIsFlip
); );
return entity; return entity;
} }
...@@ -350,15 +355,16 @@ public class PrinterDeviceBeanDao extends AbstractDao<PrinterDeviceBean, Long> { ...@@ -350,15 +355,16 @@ public class PrinterDeviceBeanDao extends AbstractDao<PrinterDeviceBean, Long> {
entity.setModel(cursor.isNull(offset + 12) ? null : cursor.getString(offset + 12)); entity.setModel(cursor.isNull(offset + 12) ? null : cursor.getString(offset + 12));
entity.setNoteContent(cursor.isNull(offset + 13) ? null : cursor.getString(offset + 13)); entity.setNoteContent(cursor.isNull(offset + 13) ? null : cursor.getString(offset + 13));
entity.setPrinterDeviceDefaultId(cursor.isNull(offset + 14) ? null : cursor.getLong(offset + 14)); entity.setPrinterDeviceDefaultId(cursor.isNull(offset + 14) ? null : cursor.getLong(offset + 14));
entity.setFlyPrinterDeviceId(cursor.isNull(offset + 15) ? null : cursor.getLong(offset + 15)); entity.setPrinterDeviceType(cursor.getInt(offset + 15));
entity.setFlyPrinterDeviceId2(cursor.isNull(offset + 16) ? null : cursor.getLong(offset + 16)); entity.setFlyPrinterDeviceId(cursor.isNull(offset + 16) ? null : cursor.getLong(offset + 16));
entity.setFoodIsBold(cursor.getInt(offset + 17)); entity.setFlyPrinterDeviceId2(cursor.isNull(offset + 17) ? null : cursor.getLong(offset + 17));
entity.setFoodFont(cursor.isNull(offset + 18) ? null : cursor.getString(offset + 18)); entity.setFoodIsBold(cursor.getInt(offset + 18));
entity.setFoodIsItalic(cursor.getInt(offset + 19)); entity.setFoodFont(cursor.isNull(offset + 19) ? null : cursor.getString(offset + 19));
entity.setModifierIsBold(cursor.getInt(offset + 20)); entity.setFoodIsItalic(cursor.getInt(offset + 20));
entity.setModifierFont(cursor.isNull(offset + 21) ? null : cursor.getString(offset + 21)); entity.setModifierIsBold(cursor.getInt(offset + 21));
entity.setModifierIsItalic(cursor.getInt(offset + 22)); entity.setModifierFont(cursor.isNull(offset + 22) ? null : cursor.getString(offset + 22));
entity.setNumberIsFlip(cursor.getInt(offset + 23)); entity.setModifierIsItalic(cursor.getInt(offset + 23));
entity.setNumberIsFlip(cursor.getInt(offset + 24));
} }
@Override @Override
......
...@@ -20,6 +20,7 @@ import android.content.res.Resources; ...@@ -20,6 +20,7 @@ import android.content.res.Resources;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.BitmapFactory; import android.graphics.BitmapFactory;
import android.graphics.Canvas; import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix; import android.graphics.Matrix;
import android.graphics.PixelFormat; import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
...@@ -28,6 +29,9 @@ import java.io.ByteArrayOutputStream; ...@@ -28,6 +29,9 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import static com.gingersoft.gsa.cloud.print.PrinterUtils.binaryStrToHexString;
import static com.gingersoft.gsa.cloud.print.PrinterUtils.hexListToByte;
/** /**
* 打印机写入器 * 打印机写入器
...@@ -436,6 +440,136 @@ public abstract class PrinterWriter { ...@@ -436,6 +440,136 @@ public abstract class PrinterWriter {
} }
/** /**
* 解码图片
*
* @param image 图片
* @param parting 高度分割值
* @return 数据流
*/
public static byte[] decodeBitmapToDataList(Bitmap image, int parting) {
if (parting <= 0 || parting > 255)
parting = 255;
if (image == null)
return null;
final int width = image.getWidth();
final int height = image.getHeight();
if (width <= 0 || height <= 0)
return null;
if (width > 2040) {
// 8位9针,宽度限制2040像素(但一般纸张都没法打印那么宽,但并不影响打印)
final float scale = 2040 / (float) width;
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
Bitmap resizeImage;
try {
resizeImage = Bitmap.createBitmap(image, 0, 0, width, height, matrix, true);
} catch (OutOfMemoryError e) {
return null;
}
resizeImage.recycle();
return decodeBitmapToDataList(resizeImage, parting);
}
// 宽命令
String widthHexString = Integer.toHexString(width % 8 == 0 ? width / 8 : (width / 8 + 1));
if (widthHexString.length() > 2) {
// 超过2040像素才会到达这里
return null;
} else if (widthHexString.length() == 1) {
widthHexString = "0" + widthHexString;
}
widthHexString += "00";
// 每行字节数(除以8,不足补0)
String zeroStr = "";
int zeroCount = width % 8;
if (zeroCount > 0) {
for (int i = 0; i < (8 - zeroCount); i++) {
//noinspection StringConcatenationInLoop
zeroStr += "0";
}
}
ArrayList<String> commandList = new ArrayList<>();
// 高度每parting像素进行一次分割
int time = height % parting == 0 ? height / parting : (height / parting + 1);// 循环打印次数
for (int t = 0; t < time; t++) {
int partHeight = t == time - 1 ? height % parting : parting;// 分段高度
// 高命令
String heightHexString = Integer.toHexString(partHeight);
if (heightHexString.length() > 2) {
// 超过255像素才会到达这里
return null;
} else if (heightHexString.length() == 1) {
heightHexString = "0" + heightHexString;
}
heightHexString += "00";
// 宽高指令
String commandHexString = "1D763000";
commandList.add(commandHexString + widthHexString + heightHexString);
ArrayList<String> list = new ArrayList<>(); //binaryString list
StringBuilder sb = new StringBuilder();
// 像素二值化,非黑即白
for (int i = 0; i < partHeight; i++) {
sb.delete(0, sb.length());
for (int j = 0; j < width; j++) {
// 实际在图片中的高度
int startHeight = t * parting + i;
//得到当前像素的值
int color = image.getPixel(j, startHeight);
int red, green, blue;
if (image.hasAlpha()) {
//得到alpha通道的值
int alpha = Color.alpha(color);
//得到图像的像素RGB的值
red = Color.red(color);
green = Color.green(color);
blue = Color.blue(color);
final float offset = alpha / 255.0f;
// 根据透明度将白色与原色叠加
red = 0xFF + (int) Math.ceil((red - 0xFF) * offset);
green = 0xFF + (int) Math.ceil((green - 0xFF) * offset);
blue = 0xFF + (int) Math.ceil((blue - 0xFF) * offset);
} else {
//得到图像的像素RGB的值
red = Color.red(color);
green = Color.green(color);
blue = Color.blue(color);
}
// 接近白色改为白色。其余黑色
if (red > 160 && green > 160 && blue > 160)
sb.append("0");
else
sb.append("1");
}
// 每一行结束时,补充剩余的0
if (zeroCount > 0) {
sb.append(zeroStr);
}
list.add(sb.toString());
}
// binaryStr每8位调用一次转换方法,再拼合
ArrayList<String> bmpHexList = new ArrayList<>();
for (String binaryStr : list) {
sb.delete(0, sb.length());
for (int i = 0; i < binaryStr.length(); i += 8) {
String str = binaryStr.substring(i, i + 8);
// 2进制转成16进制
String hexString = binaryStrToHexString(str);
sb.append(hexString);
}
bmpHexList.add(sb.toString());
}
// 数据指令
commandList.addAll(bmpHexList);
}
return hexListToByte(commandList);
}
/**
* 缩放图片 * 缩放图片
* *
* @param image 图片 * @param image 图片
......
...@@ -21,10 +21,14 @@ public class BillMethodAdapter extends BaseQuickAdapter<PayMethod, BaseViewHolde ...@@ -21,10 +21,14 @@ public class BillMethodAdapter extends BaseQuickAdapter<PayMethod, BaseViewHolde
@Override @Override
protected void convert(BaseViewHolder helper, PayMethod item) { protected void convert(BaseViewHolder helper, PayMethod item) {
QMUIAlphaTextView tv_bill_method_name = helper.getView(R.id.tv_bill_method_name); if (item != null) {
tv_bill_method_name.setText(item.getPayName()); QMUIAlphaTextView tv_bill_method_name = helper.getView(R.id.tv_bill_method_name);
tv_bill_method_name.setTextSize(item.getPayModeSize()); if(item.getPayName() != null) {
tv_bill_method_name.setTextColor(item.getPayModeTextColor()); tv_bill_method_name.setText(item.getPayName());
}
tv_bill_method_name.setTextSize(item.getPayModeSize());
tv_bill_method_name.setTextColor(item.getPayModeTextColor());
}
} }
} }
...@@ -31,8 +31,11 @@ public class BillMoneyAdapter extends BaseQuickAdapter<PayMethod, BaseViewHolder ...@@ -31,8 +31,11 @@ public class BillMoneyAdapter extends BaseQuickAdapter<PayMethod, BaseViewHolder
ImageView iv_bill_delete = helper.getView(R.id.iv_bill_delete); ImageView iv_bill_delete = helper.getView(R.id.iv_bill_delete);
TextView tv_bill_method_name = helper.getView(R.id.tv_bill_method_name); TextView tv_bill_method_name = helper.getView(R.id.tv_bill_method_name);
TextView tv_bill_money = helper.getView(R.id.tv_bill_money); TextView tv_bill_money = helper.getView(R.id.tv_bill_money);
if (datasBean != null) {
tv_bill_method_name.setText(datasBean.getPayName()); tv_bill_method_name.setText(datasBean.getPayName());
} else {
tv_bill_method_name.setText("");
}
if (datasBean.getPayMoney() < 0) { if (datasBean.getPayMoney() < 0) {
tv_bill_money.setText("-" + cashStr + Math.abs(datasBean.getPayMoney())); tv_bill_money.setText("-" + cashStr + Math.abs(datasBean.getPayMoney()));
......
...@@ -105,7 +105,7 @@ public class OrderPayView extends LinearLayout { ...@@ -105,7 +105,7 @@ public class OrderPayView extends LinearLayout {
mBillMoneyList.clear(); mBillMoneyList.clear();
// if (!mBillMoneyList.contains(method)) { // if (!mBillMoneyList.contains(method)) {
double differenceMoney = getDifferenceMoney(); double differenceMoney = getDifferenceMoney();
if (differenceMoney > -1) { if (differenceMoney > -1 && method != null) {
//補足差額 //補足差額
method.setPayMoney(differenceMoney); method.setPayMoney(differenceMoney);
} }
...@@ -270,7 +270,9 @@ public class OrderPayView extends LinearLayout { ...@@ -270,7 +270,9 @@ public class OrderPayView extends LinearLayout {
public double getBillMoney() { public double getBillMoney() {
double totalMoney = 0.0; double totalMoney = 0.0;
for (PayMethod method : mBillMoneyList) { for (PayMethod method : mBillMoneyList) {
totalMoney = MoneyUtil.sum(totalMoney, method.getPayMoney()); if (method != null) {
totalMoney = MoneyUtil.sum(totalMoney, method.getPayMoney());
}
} }
return totalMoney; return totalMoney;
} }
......
...@@ -11,6 +11,7 @@ import android.widget.TextView; ...@@ -11,6 +11,7 @@ import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication; import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.utils.other.SPUtils; import com.gingersoft.gsa.cloud.base.utils.other.SPUtils;
import com.gingersoft.gsa.cloud.base.utils.toast.ToastUtils; import com.gingersoft.gsa.cloud.base.utils.toast.ToastUtils;
...@@ -89,6 +90,7 @@ public class SwitchServerActivity extends BaseActivity<SwitchServerPresenter> im ...@@ -89,6 +90,7 @@ public class SwitchServerActivity extends BaseActivity<SwitchServerPresenter> im
}); });
switchServer.setOnClickListener(v -> { switchServer.setOnClickListener(v -> {
GsaCloudApplication.isLogin = false; GsaCloudApplication.isLogin = false;
GsaCloudApplication.clearMemberInfo();
System.exit(0); System.exit(0);
}); });
} }
......
...@@ -71,7 +71,7 @@ ...@@ -71,7 +71,7 @@
android:layout_height="@dimen/head_height" android:layout_height="@dimen/head_height"
android:layout_margin="@dimen/dp_20" android:layout_margin="@dimen/dp_20"
android:background="@color/theme_color" android:background="@color/theme_color"
android:text="切換環境" android:text="清除用戶信息"
android:textColor="@color/white" android:textColor="@color/white"
android:textSize="@dimen/sp_16" /> android:textSize="@dimen/sp_16" />
</LinearLayout> </LinearLayout>
\ No newline at end of file
...@@ -132,6 +132,14 @@ public class NewMainPresenter extends BasePresenter<NewMainContract.Model, NewMa ...@@ -132,6 +132,14 @@ public class NewMainPresenter extends BasePresenter<NewMainContract.Model, NewMa
//清空用戶信息 //清空用戶信息
GsaCloudApplication.clearMemberInfo(); GsaCloudApplication.clearMemberInfo();
} }
@Override
public void onError(Throwable t) {
super.onError(t);
mRootView.loginOut();
//清空用戶信息
GsaCloudApplication.clearMemberInfo();
}
}); });
} }
......
...@@ -249,24 +249,25 @@ public class NewMainActivity extends BaseFragmentActivity<NewMainPresenter> impl ...@@ -249,24 +249,25 @@ public class NewMainActivity extends BaseFragmentActivity<NewMainPresenter> impl
// if (!BuildConfig.DEBUG) { // if (!BuildConfig.DEBUG) {
functions.add(new Function((long) 150, 0, 5, "點餐", 0, 0)); functions.add(new Function((long) 150, 0, 5, "點餐", 0, 0));
functions.add(new Function((long) 138, 150, 5, "餐檯模式", R.drawable.ic_dining_table_mode, 0)); if (BuildConfig.DEBUG) {
functions.add(new Function((long) 138, 150, 5, "餐檯模式", R.drawable.ic_dining_table_mode, 0));
}
functions.add(new Function((long) 139, 150, 5, "外送/自取", R.drawable.ic_delivery_mode, 0)); functions.add(new Function((long) 139, 150, 5, "外送/自取", R.drawable.ic_delivery_mode, 0));
functions.add(new Function((long) 140, 150, 5, "外賣模式", R.drawable.ic_outsourcing_model_close, 0)); // functions.add(new Function((long) 140, 150, 5, "外賣模式", R.drawable.ic_outsourcing_model_close, 0));
functions.add(new Function((long) 141, 150, 5, "預點餐模式", R.drawable.ic_pre_order_mode_close, 1)); // functions.add(new Function((long) 141, 150, 5, "預點餐模式", R.drawable.ic_pre_order_mode_close, 1));
functions.add(new Function((long) 151, 0, 5, "管理", 0, 0)); functions.add(new Function((long) 151, 0, 5, "管理", 0, 0));
functions.add(new Function((long) 142, 151, 5, "賬單管理", R.drawable.ic_meals_menu_management, 0)); // functions.add(new Function((long) 142, 151, 5, "賬單管理", R.drawable.ic_meals_menu_management, 0));
functions.add(new Function((long) 142, 151, 5, "外賣接單", R.drawable.ic_takeaway_orders, 0)); // functions.add(new Function((long) 143, 151, 5, "餐檯管理", R.drawable.ic_dining_table_management, 0));
functions.add(new Function((long) 143, 151, 5, "餐檯管理", R.drawable.ic_dining_table_management, 0));
functions.add(new Function((long) 144, 151, 5, "打印管理", R.drawable.ic_print_management, 0)); functions.add(new Function((long) 144, 151, 5, "打印管理", R.drawable.ic_print_management, 0));
// functions.add(new Function((long) 145, 151, 5, "支付管理", R.drawable.ic_pay_management_close, 1)); // functions.add(new Function((long) 145, 151, 5, "支付管理", R.drawable.ic_pay_management_close, 1));
// functions.add(new Function((long) 146, 151, 5, "折扣管理", R.drawable.ic_discount_management_close, 1)); // functions.add(new Function((long) 146, 151, 5, "折扣管理", R.drawable.ic_discount_management_close, 1));
functions.add(new Function((long) 147, 151, 5, "沽清管理", R.drawable.ic_sell_off_manger, 0)); // functions.add(new Function((long) 147, 151, 5, "沽清管理", R.drawable.ic_sell_off_manger, 0));
functions.add(new Function((long) 152, 0, 5, "員工", 0, 0)); // functions.add(new Function((long) 152, 0, 5, "員工", 0, 0));
functions.add(new Function((long) 147, 152, 5, "員工管理", R.drawable.ic_staff_management_close, 1)); // functions.add(new Function((long) 147, 152, 5, "員工管理", R.drawable.ic_staff_management_close, 1));
functions.add(new Function((long) 148, 152, 5, "權限管理", R.drawable.ic_authority_management_close, 1)); // functions.add(new Function((long) 148, 152, 5, "權限管理", R.drawable.ic_authority_management_close, 1));
functions.add(new Function((long) 149, 152, 5, "操作記錄", R.drawable.ic_operation_record_close, 1)); // functions.add(new Function((long) 149, 152, 5, "操作記錄", R.drawable.ic_operation_record_close, 1));
// } else { // } else {
// functions.addAll(FunctionManager.getDefault().getFunctionByResModule(this, ComponentMain.main.class, ComponentMain.main.order, "order")); // functions.addAll(FunctionManager.getDefault().getFunctionByResModule(this, ComponentMain.main.class, ComponentMain.main.order, "order"));
// functions.addAll(FunctionManager.getDefault().getFunctionByResModule(this, ComponentMain.main.class, ComponentMain.main.manager, "manager")); // functions.addAll(FunctionManager.getDefault().getFunctionByResModule(this, ComponentMain.main.class, ComponentMain.main.manager, "manager"));
......
...@@ -287,7 +287,7 @@ class PageViewModel(private val repository: WeatherRepository) : ViewModel() { ...@@ -287,7 +287,7 @@ class PageViewModel(private val repository: WeatherRepository) : ViewModel() {
//獲取配送設置,查看當前單是否是第三方物流 //獲取配送設置,查看當前單是否是第三方物流
for (i in 0 until data.list.size) { for (i in 0 until data.list.size) {
if (data.list[i].distributionType == dataBean.deliveryMode) { if (data.list[i].distributionType == dataBean.deliveryMode) {
third = data.list[i].type == 1 third = data.list[i].type != 0
break break
} }
} }
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/> <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.BLUETOOTH" />
<application> <application>
<activity <activity
android:name=".mvp.ui.activity.PrintActivity" android:name=".mvp.ui.activity.PrintActivity"
......
...@@ -2,15 +2,14 @@ ...@@ -2,15 +2,14 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.joe.print"> package="com.joe.print">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECEIVE_USER_PRESENT" /> <uses-permission android:name="android.permission.RECEIVE_USER_PRESENT" />
<uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.INTERNET" />
<application <application
android:name="com.gingersoft.gsa.cloud.base.application.GsaCloudApplication" android:name="com.gingersoft.gsa.cloud.base.application.GsaCloudApplication"
android:allowBackup="true" android:allowBackup="true"
......
...@@ -3,6 +3,7 @@ package com.joe.print.mvp.model.bean; ...@@ -3,6 +3,7 @@ package com.joe.print.mvp.model.bean;
import android.content.Context; import android.content.Context;
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication; import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.base.utils.other.TextUtil; import com.gingersoft.gsa.cloud.base.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils; import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.database.bean.PrintCurrencyBean; import com.gingersoft.gsa.cloud.database.bean.PrintCurrencyBean;
...@@ -182,30 +183,29 @@ public class PrintInfoBean { ...@@ -182,30 +183,29 @@ public class PrintInfoBean {
* 將prj數據轉為打印類 * 將prj數據轉為打印類
* *
* @param datas prj數據 * @param datas prj數據
* @param paperWidth 紙張寬度
* @param printLocation 廚房位置 * @param printLocation 廚房位置
* @param deviceBean 打印機信息 * @param deviceBean 打印機信息
* @param printCurrencyBean 堂食or外賣配置 * @param printCurrencyBean 堂食or外賣配置
* @return 打印類集合 * @return 打印類集合
*/ */
public static List<List<PrintInfoBean>> transPrjBean(List<PrjBean.DataBean.Bean> datas, int paperWidth, String printLocation, PrinterDeviceBean deviceBean, PrintCurrencyBean printCurrencyBean) { public static List<List<PrintInfoBean>> transPrjBean(List<PrjBean.DataBean.Bean> datas, String printLocation, PrinterDeviceBean deviceBean, PrintCurrencyBean printCurrencyBean) {
List<List<PrintInfoBean>> prjPrintBeans = new ArrayList<>(); List<List<PrintInfoBean>> prjPrintBeans = new ArrayList<>();
//通過打印位置生成多張用於打印的bitmap //通過打印位置生成多張用於打印的bitmap
List<PrjBean.DataBean.Bean> noCut = new ArrayList<>();
for (PrjBean.DataBean.Bean prjbean : datas) { for (PrjBean.DataBean.Bean prjbean : datas) {
List<PrjBean.DataBean.Bean> noCut = new ArrayList<>();
//遍歷當前打印位置所有的食品 //遍歷當前打印位置所有的食品
if (prjbean.getStatus() == 2) { if (prjbean.getStatus() == 2) {
//切紙,單獨生成一條prj數據 //切紙,單獨生成一條prj數據
List<PrjBean.DataBean.Bean> beans = new ArrayList<>(); List<PrjBean.DataBean.Bean> beans = new ArrayList<>();
beans.add(prjbean); beans.add(prjbean);
prjPrintBeans.add(getPrjPrintInfoBean(printLocation, paperWidth, beans, deviceBean, printCurrencyBean)); prjPrintBeans.add(getPrjPrintInfoBean(printLocation, beans, deviceBean, printCurrencyBean));
} else { } else {
//不切紙,保存到單獨的集合里,之後生成一組數據 //不切紙,保存到單獨的集合里,之後生成一組數據
noCut.add(prjbean); noCut.add(prjbean);
} }
if (noCut.size() > 0) { }
prjPrintBeans.add(getPrjPrintInfoBean(printLocation, paperWidth, noCut, deviceBean, printCurrencyBean)); if (noCut.size() > 0) {
} prjPrintBeans.add(getPrjPrintInfoBean(printLocation, noCut, deviceBean, printCurrencyBean));
} }
return prjPrintBeans; return prjPrintBeans;
} }
...@@ -219,6 +219,7 @@ public class PrintInfoBean { ...@@ -219,6 +219,7 @@ public class PrintInfoBean {
private static int modifierFontSize = 1;//細項名字體大小 private static int modifierFontSize = 1;//細項名字體大小
private static int foodColor = 0;//食品顏色 private static int foodColor = 0;//食品顏色
private static int modifierColor = 0;//細項顏色 private static int modifierColor = 0;//細項顏色
private static int paperWidth = 24;//紙張一行顯示多少字符,默認42
private static double cnLength = 2;//中文字符占的寬度 private static double cnLength = 2;//中文字符占的寬度
private static int foodNameWidth = 21;//食品名所佔寬度 private static int foodNameWidth = 21;//食品名所佔寬度
private static int foodNumWidth = 8;//食品數量佔的寬度 private static int foodNumWidth = 8;//食品數量佔的寬度
...@@ -229,7 +230,7 @@ public class PrintInfoBean { ...@@ -229,7 +230,7 @@ public class PrintInfoBean {
* *
* @return * @return
*/ */
private static List<PrintInfoBean> getPrjPrintInfoBean(String key, int peparWidth, List<PrjBean.DataBean.Bean> prjBeans, PrinterDeviceBean deviceBean, PrintCurrencyBean printCurrencyBean) { private static List<PrintInfoBean> getPrjPrintInfoBean(String key, List<PrjBean.DataBean.Bean> prjBeans, PrinterDeviceBean deviceBean, PrintCurrencyBean printCurrencyBean) {
List<PrintInfoBean> printInfoBeans = new ArrayList<>(); List<PrintInfoBean> printInfoBeans = new ArrayList<>();
initPrintConfig(deviceBean, printCurrencyBean); initPrintConfig(deviceBean, printCurrencyBean);
if (prjBeans == null || prjBeans.size() <= 0) { if (prjBeans == null || prjBeans.size() <= 0) {
...@@ -244,35 +245,35 @@ public class PrintInfoBean { ...@@ -244,35 +245,35 @@ public class PrintInfoBean {
printInfoBeans.add(new PrintInfoBean(new String[]{"自取"}, new Boolean[]{true}, new Double[]{2d}, 0)); printInfoBeans.add(new PrintInfoBean(new String[]{"自取"}, new Boolean[]{true}, new Double[]{2d}, 0));
if (!TextUtil.isEmptyOrNullOrUndefined(prjBean.getBillNo())) { if (!TextUtil.isEmptyOrNullOrUndefined(prjBean.getBillNo())) {
//訂單碼不為空 //訂單碼不為空
printInfoBeans.add(new PrintInfoBean(new String[]{"訂單碼", prjBean.getBillNo()}, new Boolean[]{false, true}, new Double[]{1d, 2d}, 0)); printInfoBeans.add(new PrintInfoBean(new String[]{"訂單碼:", prjBean.getBillNo()}, new Boolean[]{false, true}, new Double[]{1d, 2d}, 0));
} }
if (!TextUtil.isEmptyOrNullOrUndefined(prjBean.getTakeFoodCode())) { if (!TextUtil.isEmptyOrNullOrUndefined(prjBean.getTakeFoodCode())) {
printInfoBeans.add(new PrintInfoBean(new String[]{"取餐碼", prjBean.getTakeFoodCode()}, new Boolean[]{false, true}, new Double[]{1d, 2d}, 0)); printInfoBeans.add(new PrintInfoBean(new String[]{"取餐碼:", prjBean.getTakeFoodCode()}, new Boolean[]{false, true}, new Double[]{1d, 2d}, 0));
} }
} else { } else {
printInfoBeans.add(new PrintInfoBean(new String[]{"外賣"}, new Boolean[]{true}, new Double[]{2d}, 0)); printInfoBeans.add(new PrintInfoBean(new String[]{"外賣"}, new Boolean[]{true}, new Double[]{2d}, 0));
if (!TextUtil.isEmptyOrNullOrUndefined(prjBean.getBillNo())) { if (!TextUtil.isEmptyOrNullOrUndefined(prjBean.getBillNo())) {
//訂單碼不為空 //訂單碼不為空
printInfoBeans.add(new PrintInfoBean(new String[]{"訂單碼", prjBean.getBillNo()}, new Boolean[]{false, true}, new Double[]{1d, 2d}, 0)); printInfoBeans.add(new PrintInfoBean(new String[]{"訂單碼:", prjBean.getBillNo()}, new Boolean[]{false, true}, new Double[]{1d, 2d}, 0));
} else if (!TextUtil.isEmptyOrNullOrUndefined(prjBean.getTakeFoodCode())) { } else if (!TextUtil.isEmptyOrNullOrUndefined(prjBean.getTakeFoodCode())) {
//取餐碼不為空 //取餐碼不為空
printInfoBeans.add(new PrintInfoBean(new String[]{"訂單碼", prjBean.getTakeFoodCode()}, new Boolean[]{false, true}, new Double[]{1d, 2d}, 0)); printInfoBeans.add(new PrintInfoBean(new String[]{"訂單碼:", prjBean.getTakeFoodCode()}, new Boolean[]{false, true}, new Double[]{1d, 2d}, 0));
} }
} }
} else { } else {
printInfoBeans.add(new PrintInfoBean(new String[]{prjBean.getTableName()}, new Boolean[]{true}, new Double[]{2d}, 0)); printInfoBeans.add(new PrintInfoBean(new String[]{prjBean.getTableName()}, new Boolean[]{true}, new Double[]{2d}, 0));
} }
//落單時間 //落單時間
printInfoBeans.add(new PrintInfoBean(new String[]{"落單時間" + TimeUtils.getCurrentTimeInString(TimeUtils.DEFAULT_DATE_MDHM)}, new Double[]{1d}, 0)); printInfoBeans.add(new PrintInfoBean(new String[]{"落單時間:" + TimeUtils.getCurrentTimeInString(TimeUtils.DEFAULT_DATE_MDHM)}, new Double[]{1d}, 0));
//廚房位置 //廚房位置
if (!TextUtil.isEmptyOrNullOrUndefined(key) && !key.equals("-1")) { if (!TextUtil.isEmptyOrNullOrUndefined(key) && !key.equals("-1")) {
printInfoBeans.add(new PrintInfoBean(new String[]{key + "廚房", " " + prjBean.getUserName()}, new Double[]{1d}, 0)); printInfoBeans.add(new PrintInfoBean(new String[]{key + "廚房", " " + prjBean.getUserName()}, new Double[]{1d}, 0));
} }
//人數 //人數
if (prjBean.getPerson() != 0) { if (prjBean.getPerson() != 0) {
printInfoBeans.add(new PrintInfoBean(new String[]{"人數" + prjBean.getPerson(), GsaCloudApplication.getMemberName(GsaCloudApplication.getAppContext())}, new Double[]{1d}, 0)); printInfoBeans.add(new PrintInfoBean(new String[]{"人數:" + prjBean.getPerson(), GsaCloudApplication.getMemberName(GsaCloudApplication.getAppContext())}, new Double[]{1d}, 0));
} }
printInfoBeans.add(new PrintInfoBean(new String[]{getLineBorder("", 1, peparWidth)}, 0)); printInfoBeans.add(new PrintInfoBean(new String[]{getLineBorder("", 1, paperWidth)}, 0));
for (PrjBean.DataBean.Bean bean : prjBeans) { for (PrjBean.DataBean.Bean bean : prjBeans) {
if (bean.getParentId() == 0) { if (bean.getParentId() == 0) {
//沒有父級id,則是第一級食品 //沒有父級id,則是第一級食品
...@@ -328,7 +329,7 @@ public class PrintInfoBean { ...@@ -328,7 +329,7 @@ public class PrintInfoBean {
* *
* @return * @return
*/ */
private static List<PrintInfoBean> getTakeAwayBillPrint(Context context, OrderDetails.DataBean data, PrinterDeviceBean deviceBean, PrintCurrencyBean printCurrencyBean) { public static List<PrintInfoBean> getTakeAwayBillPrint(Context context, OrderDetails.DataBean data, PrinterDeviceBean deviceBean, PrintCurrencyBean printCurrencyBean) {
List<PrintInfoBean> printInfoBeans = new ArrayList<>(); List<PrintInfoBean> printInfoBeans = new ArrayList<>();
initPrintConfig(deviceBean, printCurrencyBean); initPrintConfig(deviceBean, printCurrencyBean);
if (data == null) { if (data == null) {
...@@ -337,7 +338,7 @@ public class PrintInfoBean { ...@@ -337,7 +338,7 @@ public class PrintInfoBean {
printInfoBeans.add(new PrintInfoBean(new String[]{GsaCloudApplication.getBrandName(context)}, new Boolean[]{true}, new Double[]{2d})); printInfoBeans.add(new PrintInfoBean(new String[]{GsaCloudApplication.getBrandName(context)}, new Boolean[]{true}, new Double[]{2d}));
printInfoBeans.add(new PrintInfoBean(new String[]{GsaCloudApplication.getRestaurantName(context)}, new Boolean[]{true}, new Double[]{2d})); printInfoBeans.add(new PrintInfoBean(new String[]{GsaCloudApplication.getRestaurantName(context)}, new Boolean[]{true}, new Double[]{2d}));
printInfoBeans.add(new PrintInfoBean(new String[]{getLineBorder(data.getOrder_type() == 2 ? "外送" : "自取", 2, deviceBean.getLineFontStop())}, new Boolean[]{true}, new Double[]{2d})); printInfoBeans.add(new PrintInfoBean(new String[]{getLineBorder(data.getOrder_type() == 2 ? "外送" : "自取", 2, paperWidth)}, new Boolean[]{true}, new Double[]{2d}));
String payType = ""; String payType = "";
if (data.getOrderPayType() == 1) { if (data.getOrderPayType() == 1) {
...@@ -345,39 +346,41 @@ public class PrintInfoBean { ...@@ -345,39 +346,41 @@ public class PrintInfoBean {
} else if (data.getOrderPayType() == 0) { } else if (data.getOrderPayType() == 0) {
payType = "店內支付"; payType = "店內支付";
} else if (data.getOrderPayType() == 2) { } else if (data.getOrderPayType() == 2) {
payType = "在線支付"; payType = "在線支付:" + data.getPayName();
} }
printInfoBeans.add(new PrintInfoBean(new String[]{payType}, new Boolean[]{true}, new Double[]{2d})); printInfoBeans.add(new PrintInfoBean(new String[]{payType}, new Boolean[]{true}, new Double[]{2d}));
//送達時間或者取餐時間 //送達時間或者取餐時間
printInfoBeans.add(new PrintInfoBean(new String[]{data.getOrder_type() == 2 ? data.getSEND_TIME() : data.getTakeTime()}, new Boolean[]{true}, new Double[]{1d})); printInfoBeans.add(new PrintInfoBean(new String[]{data.getOrder_type() == 2 ? data.getSEND_TIME() : data.getTakeTime()}, new Boolean[]{true}, new Double[]{1d}));
//加線 //加線
printInfoBeans.add(new PrintInfoBean(new String[]{getLineBorder("", 2, deviceBean.getLineFontStop())}, new Double[]{2d})); printInfoBeans.add(new PrintInfoBean(new String[]{getLineBorder("", 2, paperWidth)}, new Double[]{2d}));
printInfoBeans.add(new PrintInfoBean(new String[]{"單號" + data.getORDER_NO()}, new Double[]{1d}, 0)); printInfoBeans.add(new PrintInfoBean(new String[]{"單號:" + data.getORDER_NO()}, new Double[]{1d}, 0));
if (data.getOrder_type() == 7) { if (data.getOrder_type() == 7) {
//自取 顯示 取餐碼 //自取 顯示 取餐碼
if (!TextUtil.isEmptyOrNullOrUndefined(data.getTakeFoodCode())) { if (!TextUtil.isEmptyOrNullOrUndefined(data.getTakeFoodCode())) {
printInfoBeans.add(new PrintInfoBean(new String[]{"取餐碼" + data.getTakeFoodCode()}, new Double[]{3d}, 0)); printInfoBeans.add(new PrintInfoBean(new String[]{"取餐碼:" + data.getTakeFoodCode()}, new Double[]{3d}, 0));
} }
} else { } else {
//外送 顯示訂單碼 //外送 顯示訂單碼
printInfoBeans.add(new PrintInfoBean(new String[]{"訂單碼" + data.getTakeFoodCode()}, new Double[]{3d}, 0)); printInfoBeans.add(new PrintInfoBean(new String[]{"訂單碼:" + data.getTakeFoodCode()}, new Double[]{3d}, 0));
} }
printInfoBeans.add(new PrintInfoBean(new String[]{"單號" + data.getORDER_NO()}, new Double[]{1d}, 0)); printInfoBeans.add(new PrintInfoBean(new String[]{"單號:" + data.getORDER_NO()}, new Double[]{1d}, 0));
//開單時間 //開單時間
printInfoBeans.add(new PrintInfoBean(new String[]{context.getString(R.string.create_order_time) + TimeUtils.parseTimeRepeat(data.getCREATE_TIME(), TimeUtils.DEFAULT_DATE_FORMAT)}, new Double[]{1d}, 0)); printInfoBeans.add(new PrintInfoBean(new String[]{context.getString(R.string.create_order_time) + TimeUtils.parseTimeRepeat(data.getCREATE_TIME(), TimeUtils.DEFAULT_DATE_FORMAT)}, new Double[]{1d}, 0));
//支付時間
if (data.getOrderPayType() == 2) { if (data.getOrderPayType() == 2) {
//支付時間
if (data.getPayTime() != null) { if (data.getPayTime() != null) {
printInfoBeans.add(new PrintInfoBean(new String[]{"支付時間" + data.getPayTime()}, new Double[]{1d}, 0)); printInfoBeans.add(new PrintInfoBean(new String[]{"支付時間:" + data.getPayTime()}, new Double[]{1d}, 0));
} }
} }
//備註
if (data.getRemark() != null && !data.getRemark().isEmpty()) {
printInfoBeans.add(new PrintInfoBean(new String[]{"備註:" + data.getRemark()}, new Double[]{1d}, 0));
}
//下面開始打印食品 //下面開始打印食品
printInfoBeans.add(new PrintInfoBean(new String[]{getLineBorder("項目", 1, deviceBean.getLineFontStop())}, new Double[]{1d})); printInfoBeans.add(new PrintInfoBean(new String[]{getLineBorder("項目", 1, paperWidth)}, new Double[]{1d}));
if (data.getPRODUCT_NAME() != null) { if (data.getPRODUCT_NAME() != null) {
for (OrderDetails.DataBean.PRODUCTNAMEBean productnameBean : data.getPRODUCT_NAME()) { for (OrderDetails.DataBean.PRODUCTNAMEBean productnameBean : data.getPRODUCT_NAME()) {
...@@ -388,12 +391,39 @@ public class PrintInfoBean { ...@@ -388,12 +391,39 @@ public class PrintInfoBean {
if (foodName != null) { if (foodName != null) {
if (getChineseValueLength(foodName) > foodNameWidth) { if (getChineseValueLength(foodName) > foodNameWidth) {
//如果食品名的長度大於設定的最大長度 //如果食品名的長度大於設定的最大長度
printInfoBeans.add(new PrintInfoBean(new String[]{MyPrintUtils.getFormatText(foodName, foodNameWidth), getSpaceByTextLength(foodNum, foodNumWidth) + foodNum, getSpaceByTextLength(foodPrice, foodPriceWidth) + foodPrice}, new Double[]{1d})); printInfoBeans.add(new PrintInfoBean(new String[]{MyPrintUtils.getFormatText(foodName, foodNameWidth), getSpaceByTextLength(foodNum, foodNumWidth) + foodNum, getSpaceByTextLength(foodPrice, foodPriceWidth) + foodPrice}, new Double[]{1d}, 0));
} else { } else {
printInfoBeans.add(new PrintInfoBean(new String[]{foodName + getSpaceByTextLength(foodName, foodNameWidth), getSpaceByTextLength(foodNum, foodNumWidth) + foodNum, getSpaceByTextLength(foodPrice, foodPriceWidth) + foodPrice}, new Double[]{1d})); printInfoBeans.add(new PrintInfoBean(new String[]{foodName + getSpaceByTextLength(foodName, foodNameWidth), getSpaceByTextLength(foodNum, foodNumWidth) + foodNum, getSpaceByTextLength(foodPrice, foodPriceWidth) + foodPrice}, new Double[]{1d}, 0));
}
}
if (productnameBean.getChild() != null) {
for (OrderDetails.DataBean.PRODUCTNAMEBean.ChildBeanX childBeanX : productnameBean.getChild()) {
//遍歷一級細項
String childFoodName = " -" + childBeanX.getPRODUCT_NAME();
String childFoodNum = "X" + childBeanX.getNum();
String childFoodPrice = childBeanX.getPRICE();
if (getChineseValueLength(childFoodName) > foodNameWidth) {
//如果食品名的長度大於設定的最大長度
printInfoBeans.add(new PrintInfoBean(new String[]{MyPrintUtils.getFormatText(childFoodName, foodNameWidth), getSpaceByTextLength(childFoodNum, foodNumWidth) + childFoodNum, getSpaceByTextLength(childFoodPrice, foodPriceWidth) + childFoodPrice}, new Double[]{1d}, 0));
} else {
printInfoBeans.add(new PrintInfoBean(new String[]{childFoodName + getSpaceByTextLength(childFoodName, foodNameWidth), getSpaceByTextLength(childFoodNum, foodNumWidth) + childFoodNum, getSpaceByTextLength(childFoodPrice, foodPriceWidth) + childFoodPrice}, new Double[]{1d}, 0));
}
if (childBeanX.getChild() != null) {
for (OrderDetails.DataBean.PRODUCTNAMEBean.ChildBeanX.ChildBean childBean : childBeanX.getChild()) {
//遍歷一級細項
String secondChildFoodName = " -" + childBean.getPRODUCT_NAME();
String secondChildFoodNum = "X" + childBean.getNum();
String secondChildFoodPrice = childBean.getPRICE();
if (getChineseValueLength(secondChildFoodName) > foodNameWidth) {
//如果食品名的長度大於設定的最大長度
printInfoBeans.add(new PrintInfoBean(new String[]{MyPrintUtils.getFormatText(secondChildFoodName, foodNameWidth), getSpaceByTextLength(secondChildFoodNum, foodNumWidth) + secondChildFoodNum, getSpaceByTextLength(secondChildFoodPrice, foodPriceWidth) + secondChildFoodPrice}, new Double[]{1d}, 0));
} else {
printInfoBeans.add(new PrintInfoBean(new String[]{secondChildFoodName + getSpaceByTextLength(secondChildFoodName, foodNameWidth), getSpaceByTextLength(secondChildFoodNum, foodNumWidth) + secondChildFoodNum, getSpaceByTextLength(secondChildFoodPrice, foodPriceWidth) + secondChildFoodPrice}, new Double[]{1d}, 0));
}
}
}
} }
} }
// for (OrderDetails.DataBean.PRODUCTNAMEBean.ChildBeanX childBeanX : item.getChild()) { // for (OrderDetails.DataBean.PRODUCTNAMEBean.ChildBeanX childBeanX : item.getChild()) {
// View secondView = getChild(childBeanX.getPRODUCT_NAME(), childBeanX.getNum(), childBeanX.getPRICE(), indentation); // View secondView = getChild(childBeanX.getPRODUCT_NAME(), childBeanX.getNum(), childBeanX.getPRICE(), indentation);
// childLayout.addView(secondView); // childLayout.addView(secondView);
...@@ -406,21 +436,35 @@ public class PrintInfoBean { ...@@ -406,21 +436,35 @@ public class PrintInfoBean {
// } // }
} }
} }
printInfoBeans.add(new PrintInfoBean(new String[]{"支付時間:" + data.getPayTime()}, new Double[]{1d}, 0)); printInfoBeans.add(new PrintInfoBean(new String[]{getLineBorder("", 1, paperWidth)}, new Double[]{1d}));
//
// //計算金額 printInfoBeans.add(new PrintInfoBean(new String[]{getLeftRightText("合計啊啥的和發哈是打飛機:", "$" + MoneyUtil.sub(MoneyUtil.sub(Double.parseDouble(data.getTOTAL_AMOUNT()), data.getLunchbox()), data.getDELIVERY_CHARGE()), paperWidth)}, new Boolean[]{false}, new Double[]{1d}));
// billData.add(getBillBean("合計:", amountUnit + MoneyUtil.sub(MoneyUtil.sub(Double.parseDouble(data.getTOTAL_AMOUNT()), data.getLunchbox()), data.getDELIVERY_CHARGE())));
// if (data.getLunchbox() != 0) { if (data.getLunchbox() != 0) {
// billData.add(getBillBean("餐盒費:", amountUnit + data.getLunchbox())); printInfoBeans.add(new PrintInfoBean(new String[]{getLeftRightText("餐盒費啊啥的和發哈是打飛機:", "$" + data.getLunchbox(), paperWidth)}, new Boolean[]{false}, new Double[]{1d}));
// } }
// if (data.getDELIVERY_CHARGE() != 0) { if (data.getDELIVERY_CHARGE() != 0) {
// billData.add(getBillBean("送貨費:", amountUnit + data.getDELIVERY_CHARGE())); printInfoBeans.add(new PrintInfoBean(new String[]{getLeftRightText("送貨費啊啥的和發哈是打飛機:", "$" + data.getDELIVERY_CHARGE(), paperWidth)}, new Boolean[]{false}, new Double[]{1d}));
// } }
// if (data.getCouponList() != null && data.getCouponList().size() > 0) { if (data.getCouponList() != null && data.getCouponList().size() > 0) {
// for (OrderDetails.DataBean.CouponBean coupon : data.getCouponList()) { for (OrderDetails.DataBean.CouponBean coupon : data.getCouponList()) {
// billData.add(getBillBean(coupon.getCouponName() + ":", "-$" + coupon.getDiscount_amount())); printInfoBeans.add(new PrintInfoBean(new String[]{getLeftRightText(coupon.getCouponName() + ":", "-$" + coupon.getDiscount_amount(), paperWidth)}, new Boolean[]{false}, new Double[]{1d}));
// } }
// } }
printInfoBeans.add(new PrintInfoBean(new String[]{getLeftRightText("總金額啊啥的和發哈是打飛機:", "$" + data.getTOTAL_AMOUNT(), paperWidth / 2)}, new Boolean[]{true}, new Double[]{2d}));
printInfoBeans.add(new PrintInfoBean(new String[]{getLineBorder("", 1, paperWidth)}, new Double[]{1d}));
printInfoBeans.add(new PrintInfoBean(new String[]{"支付金額:", "$" + MoneyUtil.sub(Double.parseDouble(data.getTOTAL_AMOUNT()), data.getDiscount_amount())}, new Boolean[]{true}, new Double[]{2d}, 0));
printInfoBeans.add(new PrintInfoBean(new String[]{getLineBorder("", 1, paperWidth)}, new Double[]{1d}));
if (data.getOrder_type() == 2) {
printInfoBeans.add(new PrintInfoBean(new String[]{context.getString(R.string.address) + data.getAddressDetail()}, 0));
printInfoBeans.add(new PrintInfoBean(new String[]{"收貨人:" + data.getRECEIVER()}, 0));
}
//手機號
printInfoBeans.add(new PrintInfoBean(new String[]{"手機號:" + data.getPHONE()}, 0));
return printInfoBeans; return printInfoBeans;
} }
...@@ -432,15 +476,27 @@ public class PrintInfoBean { ...@@ -432,15 +476,27 @@ public class PrintInfoBean {
* @param maxLength 最大長度 * @param maxLength 最大長度
* @return * @return
*/ */
// private static String getLeftRightText(String leftText, String rightText, int maxLength) { private static String getLeftRightText(String leftText, String rightText, int maxLength) {
// int leftLength = maxLength / 2 - 2; int leftMaxLength = maxLength / 2 - 2;
// if (getChineseValueLength(leftText) > leftLength) { int leftLength = (int) getChineseValueLength(leftText);
// //如果左側文本的長度大於設定的最大長度,換行 StringBuilder stringBuilder = new StringBuilder();
// if (getChineseValueLength(leftText) > leftMaxLength) {
// } //如果左側文本的長度大於設定的最大長度,換行
// List<String> stringList = getFormatList(leftText, maxLength);
// for (int i = 0; i < stringList.size(); i++) {
// } stringBuilder.append(stringList.get(i));
if (i == 0) {
stringBuilder.append(getSpaceByTextLength(rightText, leftMaxLength));
stringBuilder.append(rightText);
}
}
} else {
stringBuilder.append(leftText);
stringBuilder.append(getSpaceByTextLength(rightText, maxLength - leftLength));
stringBuilder.append(rightText);
}
return stringBuilder.toString();
}
/** /**
...@@ -506,10 +562,11 @@ public class PrintInfoBean { ...@@ -506,10 +562,11 @@ public class PrintInfoBean {
cnLength = 2; cnLength = 2;
} }
if (deviceBean.getLineFontStop() > 0) { if (deviceBean.getLineFontStop() > 0) {
foodNameWidth = (int) (deviceBean.getLineFontStop() * 0.5); paperWidth = deviceBean.getLineFontStop();
foodNumWidth = (int) (deviceBean.getLineFontStop() * 0.2);
foodPriceWidth = (int) (deviceBean.getLineFontStop() * 0.3);
} }
foodNameWidth = (int) (paperWidth * 0.5);
foodNumWidth = (int) (paperWidth * 0.2);
foodPriceWidth = (int) (paperWidth * 0.3);
} }
...@@ -524,6 +581,8 @@ public class PrintInfoBean { ...@@ -524,6 +581,8 @@ public class PrintInfoBean {
private static String getLineBorder(String text, double fontSize, int paperWidth) { private static String getLineBorder(String text, double fontSize, int paperWidth) {
if (fontSize == 0) { if (fontSize == 0) {
fontSize = 1; fontSize = 1;
} else if (fontSize == 2) {
fontSize = 1.5;
} }
//中文字符個數,Epson打印機每個中文字符佔1.5格 //中文字符個數,Epson打印機每個中文字符佔1.5格
double cnCount = getChineseValueLength(text); double cnCount = getChineseValueLength(text);
...@@ -542,6 +601,55 @@ public class PrintInfoBean { ...@@ -542,6 +601,55 @@ public class PrintInfoBean {
return builder.toString(); return builder.toString();
} }
private static String abc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
/**
* 如果超過紙張寬度的英文,換行時,要截取得當
* 23
*
* @return
*/
public static List<String> getFormatList(String content, int paperWidth) {
List<String> stringList = new ArrayList<>();
if (content.length() > paperWidth) {
int lastIndex = 0;//上次截取時最後的下標
while (true) {
if (lastIndex + paperWidth >= content.length()) {
String footStr = content.substring(lastIndex);
stringList.add(footStr);
return stringList;
} else {
String headerStr = content.substring(lastIndex, lastIndex + paperWidth);
String nextContext = content.substring(lastIndex + paperWidth, lastIndex + paperWidth + 1);
if (abc.contains(headerStr.charAt(headerStr.length() - 1) + "") && abc.contains(nextContext)) {
//如果最後一位是英文單詞,往前找找到空格或者不是英文的,然後換行
for (int j = headerStr.length() - 1; j >= 0; j--) {
String tchar = headerStr.charAt(j) + "";
if (j == 0) {
//循環完了都沒找到,就不管了
stringList.add(headerStr);
lastIndex += paperWidth;
break;
}
if (!abc.contains(tchar)) {
//找到不是英文的那個
String newHeaderStr = headerStr.substring(0, j + 1);
stringList.add(newHeaderStr);
lastIndex += j + 1;
break;
}
}
} else {
lastIndex += paperWidth;
stringList.add(headerStr);
}
}
}
} else {
return stringList;
}
}
/** /**
* 根據字符串獲取長度,中文長度為2,在那台針式打印機長度為1.5 * 根據字符串獲取長度,中文長度為2,在那台針式打印機長度為1.5
* *
......
package com.joe.print.mvp.presenter; package com.joe.print.mvp.presenter;
import android.app.Application; import android.app.Application;
import android.content.Context;
import android.util.Log; import android.util.Log;
import com.gingersoft.gsa.cloud.base.common.bean.BaseResult; import com.gingersoft.gsa.cloud.base.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.base.common.bean.PrinterManger.PrinterManager; import com.gingersoft.gsa.cloud.base.common.bean.PrinterManger.PrinterManager;
import com.gingersoft.gsa.cloud.base.utils.JsonUtils; import com.gingersoft.gsa.cloud.base.utils.JsonUtils;
import com.gingersoft.gsa.cloud.base.utils.other.SPUtils;
import com.gingersoft.gsa.cloud.database.bean.PrintCurrencyBean;
import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean; import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean;
import com.gingersoft.gsa.cloud.database.bean.PrinterListBean; import com.gingersoft.gsa.cloud.database.bean.PrinterListBean;
import com.gingersoft.gsa.cloud.database.utils.PrintCurrencyDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.PrinterDeviceDaoUtils;
import com.jess.arms.di.scope.ActivityScope; import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader; import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager; import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter; import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils; import com.jess.arms.utils.RxLifecycleUtils;
import com.joe.print.mvp.contract.PrintContract; import com.joe.print.mvp.contract.PrintContract;
import com.joe.print.mvp.model.bean.PrjBean;
import com.joe.print.mvp.print.PrintBill;
import com.joe.print.mvp.print.PrintCleanMachine;
import com.joe.print.mvp.print.PrintInstruction;
import com.joe.print.mvp.print.PrintOtherOrder;
import com.joe.print.mvp.print.PrintOtherOrderClosing;
import com.joe.print.mvp.print.PrintPrjKitchen;
import com.joe.print.mvp.print.PrintServe;
import com.joe.print.mvp.print.PrintSlip;
import com.joe.print.mvp.print.PrintTest;
import com.joe.print.mvp.print.PrinterRoot;
import com.joe.print.mvp.print.utils.MyPrintUtils;
import java.util.List; import java.util.List;
...@@ -24,6 +41,8 @@ import io.reactivex.schedulers.Schedulers; ...@@ -24,6 +41,8 @@ import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler; import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber; import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import static com.joe.print.mvp.print.PrinterRoot.PRINT_TEST;
/** /**
* ================================================ * ================================================
...@@ -48,6 +67,11 @@ public class PrintPresenter extends BasePresenter<PrintContract.Model, PrintCont ...@@ -48,6 +67,11 @@ public class PrintPresenter extends BasePresenter<PrintContract.Model, PrintCont
@Inject @Inject
AppManager mAppManager; AppManager mAppManager;
//通用配置
private PrintCurrencyBean printCurrencyBean;
//默認打印機
private PrinterDeviceBean printerDeviceBean;
@Inject @Inject
public PrintPresenter(PrintContract.Model model, PrintContract.View rootView) { public PrintPresenter(PrintContract.Model model, PrintContract.View rootView) {
super(model, rootView); super(model, rootView);
...@@ -80,7 +104,7 @@ public class PrintPresenter extends BasePresenter<PrintContract.Model, PrintCont ...@@ -80,7 +104,7 @@ public class PrintPresenter extends BasePresenter<PrintContract.Model, PrintCont
public void onNext(BaseResult baseResult) { public void onNext(BaseResult baseResult) {
if (baseResult.isSuccess()) { if (baseResult.isSuccess()) {
PrinterListBean deviceBeans = JsonUtils.parseObject(baseResult.getData(), PrinterListBean.class); PrinterListBean deviceBeans = JsonUtils.parseObject(baseResult.getData(), PrinterListBean.class);
if(deviceBeans != null){ if (deviceBeans != null) {
//有打印機,返回true //有打印機,返回true
PrinterManager.getPrinterManager().setDeviceBeans(deviceBeans.getList()); PrinterManager.getPrinterManager().setDeviceBeans(deviceBeans.getList());
mRootView.showPrinterList(deviceBeans.getList()); mRootView.showPrinterList(deviceBeans.getList());
...@@ -99,4 +123,75 @@ public class PrintPresenter extends BasePresenter<PrintContract.Model, PrintCont ...@@ -99,4 +123,75 @@ public class PrintPresenter extends BasePresenter<PrintContract.Model, PrintCont
} }
}); });
} }
public List<PrinterDeviceBean> getAllPrintList(Context context) {
PrinterDeviceDaoUtils printerDeviceDaoUtils = new PrinterDeviceDaoUtils(context);
return printerDeviceDaoUtils.queryAllPrinterDeviceBean();
}
/**
* 通過類型獲取打印通用配置
*
* @param context
* @param type 1:堂食,2:外送
* @return
*/
public PrintCurrencyBean getPrintCurrencyBeanByType(Context context, int type) {
PrintCurrencyDaoUtils printCurrencyDaoUtils = new PrintCurrencyDaoUtils(context);
List<PrintCurrencyBean> printCurrencyBeans = printCurrencyDaoUtils.queryAllPrintCurrencyBean();
for (PrintCurrencyBean printCurrencyBean : printCurrencyBeans) {
if (printCurrencyBean.getType() == type) {
return printCurrencyBean;
}
}
return null;
}
public PrinterDeviceBean getDefaultPrintInList(List<PrinterDeviceBean> printerDeviceBeans, String printDeviceName) {
if (printerDeviceBeans != null) {
for (PrinterDeviceBean printerDeviceBean : printerDeviceBeans) {
if (printerDeviceBean.getPrinterDeviceDefaultId() != null) {
//默認打印機
this.printerDeviceBean = printerDeviceBean;
return this.printerDeviceBean;
}
}
//沒有設置默認打印機,取用戶最近使用的打印機
for (PrinterDeviceBean printerDeviceBean : printerDeviceBeans) {
if (printDeviceName != null && printDeviceName.equals(printerDeviceBean.getName())) {
this.printerDeviceBean = printerDeviceBean;
return this.printerDeviceBean;
}
}
//沒有設置默認打印機,也沒有最近使用的打印機,並且如果打印機數量為1,就取這一台
if (printerDeviceBeans.size() == 1) {
return printerDeviceBeans.get(0);
}
}
return printerDeviceBean;
}
public PrinterRoot getPrinterByType(int type) {
if (type == PrinterRoot.PRINT_TEST) {
return new PrintTest();
} else if (type == PrinterRoot.PRINT_SERVE) {
return new PrintServe();
} else if (type == PrinterRoot.PRINT_SLIP) {
return new PrintSlip();
} else if (type == PrinterRoot.PRINT_BILL) {
return new PrintBill();
} else if (type == PrinterRoot.PRINT_KITCHEN) {
return new PrintPrjKitchen();
} else if (type == PrinterRoot.PRINT_CLEAN_MACHINE) {
return new PrintCleanMachine();
} else if (type == PrinterRoot.PRINT_OTHER_ORDER) {
return new PrintOtherOrder();
} else if (type == PrinterRoot.PRINT_INSTRUCTION) {
return new PrintInstruction();
} else if (type == PrinterRoot.PRINT_OTHER_CLOSING) {
return new PrintOtherOrderClosing();
}
return null;
}
} }
...@@ -485,16 +485,13 @@ public class EpsonPrint implements ReceiveListener { ...@@ -485,16 +485,13 @@ public class EpsonPrint implements ReceiveListener {
public void onPtrReceive(Printer printer, int i, PrinterStatusInfo printerStatusInfo, String s) { public void onPtrReceive(Printer printer, int i, PrinterStatusInfo printerStatusInfo, String s) {
this.mPrinter = printer; this.mPrinter = printer;
mPrinter.clearCommandBuffer(); mPrinter.clearCommandBuffer();
Log.e(TAG, "1111回調,還剩下:" + bitmaps.size() + "未打印,連接狀態:" + printerStatusInfo.getConnection());
resetCount = 5; resetCount = 5;
Log.e(TAG, "2222打印成功,還剩下:" + bitmaps.size() + "未打印" + s);
if (timerDisposable != null && !timerDisposable.isDisposed()) { if (timerDisposable != null && !timerDisposable.isDisposed()) {
timerDisposable.dispose(); timerDisposable.dispose();
} }
if (bitmaps.size() > 0) { if (bitmaps.size() > 0) {
bitmaps.remove(0); bitmaps.remove(0);
} }
Log.e(TAG, "3333打印完成,還剩下:" + bitmaps.size() + "未打印");
if (bitmaps.size() > 0) { if (bitmaps.size() > 0) {
// startTimer(2); // startTimer(2);
printData(ipAddress, bitmaps.get(0)); printData(ipAddress, bitmaps.get(0));
......
...@@ -22,6 +22,8 @@ import com.gingersoft.gsa.cloud.base.common.bean.mealManage.MyOrderManage; ...@@ -22,6 +22,8 @@ import com.gingersoft.gsa.cloud.base.common.bean.mealManage.MyOrderManage;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.OpenTableManage; import com.gingersoft.gsa.cloud.base.common.bean.mealManage.OpenTableManage;
import com.gingersoft.gsa.cloud.base.utils.MoneyUtil; import com.gingersoft.gsa.cloud.base.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils; import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.base.utils.view.ImageUtils;
import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean;
import com.joe.print.R; import com.joe.print.R;
import java.math.BigDecimal; import java.math.BigDecimal;
...@@ -36,7 +38,7 @@ import java.util.Map; ...@@ -36,7 +38,7 @@ import java.util.Map;
public class PrintBill extends PrinterRoot { public class PrintBill extends PrinterRoot {
@Override @Override
public Map<String, List<Bitmap>> getPrintBitmap(Context mContext) { public Map<String, List<Bitmap>> getPrintBitmap(Context mContext, PrinterDeviceBean deviceBean) {
Map<String, List<Bitmap>> bitmapMaps = new HashMap<>(); Map<String, List<Bitmap>> bitmapMaps = new HashMap<>();
List<Bitmap> bitmaps = new ArrayList<>(); List<Bitmap> bitmaps = new ArrayList<>();
bitmaps.add(getServeBitmap(mContext)); bitmaps.add(getServeBitmap(mContext));
...@@ -49,7 +51,6 @@ public class PrintBill extends PrinterRoot { ...@@ -49,7 +51,6 @@ public class PrintBill extends PrinterRoot {
return 1; return 1;
} }
/** /**
* 獲取"結賬單"圖片 * 獲取"結賬單"圖片
* *
...@@ -93,7 +94,7 @@ public class PrintBill extends PrinterRoot { ...@@ -93,7 +94,7 @@ public class PrintBill extends PrinterRoot {
List<BillingBean> billingBeans = new ArrayList<>(); List<BillingBean> billingBeans = new ArrayList<>();
//添加合計項 //添加合計項
billingBeans.add(new BillingBean("合計",MyOrderManage.getInstance().getWholeAmount())); billingBeans.add(new BillingBean("合計", MyOrderManage.getInstance().getWholeAmount()));
//添加其他金額項 //添加其他金額項
if (MyOrderManage.getInstance().getOrderMoneyList().size() > 0) { if (MyOrderManage.getInstance().getOrderMoneyList().size() > 0) {
for (BillOrderMoney item : MyOrderManage.getInstance().getOrderMoneyList()) { for (BillOrderMoney item : MyOrderManage.getInstance().getOrderMoneyList()) {
...@@ -132,4 +133,58 @@ public class PrintBill extends PrinterRoot { ...@@ -132,4 +133,58 @@ public class PrintBill extends PrinterRoot {
// ivBarCode.setImageBitmap(BitmapUtil.generateBitmap("12312112131", 2, 450, 150)); // ivBarCode.setImageBitmap(BitmapUtil.generateBitmap("12312112131", 2, 450, 150));
return viewToBitmap(context, view); return viewToBitmap(context, view);
} }
private Bitmap getBitmap(Context mContext, PrinterDeviceBean deviceBean) {
List<OrderDetail> foodList = MyOrderManage.getInstance().getOrderFoodList();
TableBean.DataBean tableBean = OpenTableManage.getDefault().getTableBean();
LinearLayout layout = new LinearLayout(mContext);
layout.setOrientation(LinearLayout.VERTICAL);
//訂單頭
layout.addView(getHeader(mContext));
layout.addView(getLine(mContext));
//訂單信息
String tableName = "餐檯:" + tableBean.getTableName();
String peopleNum = OpenTableManage.getDefault().getPeopleNumber() + "";
String orderNum = null;
if (MyOrderManage.getInstance().getOrderId() != -1) {
orderNum = MyOrderManage.getInstance().getOrderId() + "";
}
String createTime = TimeUtils.parseTimeRepeat(tableBean.getCreateTime(), TimeUtils.DEFAULT_DATE_FORMAT);
layout.addView(getDiningTableOrderInfo(mContext, tableName, peopleNum, orderNum, createTime));
layout.addView(getLine(mContext));
//食品信息
layout.addView(getDiningFoodList(mContext, foodList));
layout.addView(getHalfLine(mContext));
//訂單金額信息
List<BillingBean> billingBeans = new ArrayList<>();
//添加合計項
billingBeans.add(new BillingBean("合計", MyOrderManage.getInstance().getWholeAmount()));
//添加其他金額項
if (MyOrderManage.getInstance().getOrderMoneyList().size() > 0) {
for (BillOrderMoney item : MyOrderManage.getInstance().getOrderMoneyList()) {
billingBeans.add(new BillingBean(item.getTitle(), item.getMoney()));
}
}
layout.addView(getDiningBillInfo(mContext, billingBeans));
layout.addView(getHalfLine(mContext));
BigDecimal totalAmount = new BigDecimal(0);
for (OrderDetail OrderDetail : MyOrderManage.getInstance().getOrderFoodList()) {
totalAmount = MoneyUtil.sum(totalAmount, OrderDetail.getPrice());
}
layout.addView(getAmountText(mContext, "總金額:" + totalAmount));
// layout.addView();
layout.addView(getLine(mContext));
layout.addView(getDiningBillPayMethod(mContext, MyOrderManage.getInstance().getBillMoney()));
layout.addView(getLine(mContext));
return zoomBitmap(deviceBean, viewToBitmap(mContext, layout));
}
} }
...@@ -5,6 +5,7 @@ import android.graphics.Bitmap; ...@@ -5,6 +5,7 @@ import android.graphics.Bitmap;
import android.view.View; import android.view.View;
import com.gingersoft.gsa.cloud.base.utils.PrintTransitUtils; import com.gingersoft.gsa.cloud.base.utils.PrintTransitUtils;
import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
...@@ -17,7 +18,7 @@ import java.util.Map; ...@@ -17,7 +18,7 @@ import java.util.Map;
public class PrintCleanMachine extends PrinterRoot { public class PrintCleanMachine extends PrinterRoot {
@Override @Override
public Map<String, List<Bitmap>> getPrintBitmap(Context mContext) { public Map<String, List<Bitmap>> getPrintBitmap(Context mContext, PrinterDeviceBean deviceBean) {
Map<String, List<Bitmap>> bitmapMaps = new HashMap<>(); Map<String, List<Bitmap>> bitmapMaps = new HashMap<>();
List<Bitmap> bitmaps = new ArrayList<>(); List<Bitmap> bitmaps = new ArrayList<>();
bitmaps.add(getServeBitmap(mContext)); bitmaps.add(getServeBitmap(mContext));
......
...@@ -3,6 +3,8 @@ package com.joe.print.mvp.print; ...@@ -3,6 +3,8 @@ package com.joe.print.mvp.print;
import android.content.Context; import android.content.Context;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
...@@ -12,7 +14,7 @@ import java.util.Map; ...@@ -12,7 +14,7 @@ import java.util.Map;
public class PrintInstruction extends PrinterRoot { public class PrintInstruction extends PrinterRoot {
@Override @Override
public Map<String, List<Bitmap>> getPrintBitmap(Context mContext) { public Map<String, List<Bitmap>> getPrintBitmap(Context mContext, PrinterDeviceBean deviceBean) {
return null; return null;
} }
......
...@@ -16,6 +16,7 @@ import com.gingersoft.gsa.cloud.base.common.bean.mealManage.MyOrderManage; ...@@ -16,6 +16,7 @@ import com.gingersoft.gsa.cloud.base.common.bean.mealManage.MyOrderManage;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.OpenTableManage; import com.gingersoft.gsa.cloud.base.common.bean.mealManage.OpenTableManage;
import com.gingersoft.gsa.cloud.base.utils.other.TextUtil; import com.gingersoft.gsa.cloud.base.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils; import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean;
import com.joe.print.R; import com.joe.print.R;
import java.util.ArrayList; import java.util.ArrayList;
...@@ -30,7 +31,7 @@ import java.util.Objects; ...@@ -30,7 +31,7 @@ import java.util.Objects;
public class PrintKitchen extends PrinterRoot { public class PrintKitchen extends PrinterRoot {
@Override @Override
public Map<String, List<Bitmap>> getPrintBitmap(Context mContext) { public Map<String, List<Bitmap>> getPrintBitmap(Context mContext, PrinterDeviceBean deviceBean) {
Map<String, List<Bitmap>> bitmapMaps = new HashMap<>(); Map<String, List<Bitmap>> bitmapMaps = new HashMap<>();
List<OrderDetail> orderDetails = MyOrderManage.getInstance().getNewFoodList(); List<OrderDetail> orderDetails = MyOrderManage.getInstance().getNewFoodList();
if (orderDetails != null) { if (orderDetails != null) {
......
...@@ -17,6 +17,7 @@ import com.gingersoft.gsa.cloud.base.utils.other.TextUtil; ...@@ -17,6 +17,7 @@ import com.gingersoft.gsa.cloud.base.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils; import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.constans.ExpandConstant; import com.gingersoft.gsa.cloud.constans.ExpandConstant;
import com.gingersoft.gsa.cloud.database.bean.ExpandInfo; import com.gingersoft.gsa.cloud.database.bean.ExpandInfo;
import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean;
import com.gingersoft.gsa.cloud.database.utils.ExpandInfoDaoUtils; import com.gingersoft.gsa.cloud.database.utils.ExpandInfoDaoUtils;
import com.gingersoft.gsa.cloud.print.bean.OrderDetails; import com.gingersoft.gsa.cloud.print.bean.OrderDetails;
import com.joe.print.R; import com.joe.print.R;
...@@ -34,7 +35,7 @@ public class PrintOtherOrder extends PrinterRoot { ...@@ -34,7 +35,7 @@ public class PrintOtherOrder extends PrinterRoot {
@Override @Override
public Map<String, List<Bitmap>> getPrintBitmap(Context mContext) { public Map<String, List<Bitmap>> getPrintBitmap(Context mContext, PrinterDeviceBean deviceBean) {
OrderDetails.DataBean dataBean = MyOrderManage.getDataBean(); OrderDetails.DataBean dataBean = MyOrderManage.getDataBean();
if (dataBean != null) { if (dataBean != null) {
Map<String, List<Bitmap>> bitmapMaps = new HashMap<>(); Map<String, List<Bitmap>> bitmapMaps = new HashMap<>();
......
...@@ -15,6 +15,7 @@ import com.gingersoft.gsa.cloud.base.utils.MoneyUtil; ...@@ -15,6 +15,7 @@ import com.gingersoft.gsa.cloud.base.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils; import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.constans.ExpandConstant; import com.gingersoft.gsa.cloud.constans.ExpandConstant;
import com.gingersoft.gsa.cloud.database.bean.ExpandInfo; import com.gingersoft.gsa.cloud.database.bean.ExpandInfo;
import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean;
import com.gingersoft.gsa.cloud.database.utils.ExpandInfoDaoUtils; import com.gingersoft.gsa.cloud.database.utils.ExpandInfoDaoUtils;
import com.gingersoft.gsa.cloud.print.bean.OrderDetails; import com.gingersoft.gsa.cloud.print.bean.OrderDetails;
import com.joe.print.R; import com.joe.print.R;
...@@ -33,7 +34,7 @@ import java.util.Map; ...@@ -33,7 +34,7 @@ import java.util.Map;
public class PrintOtherOrderClosing extends PrinterRoot { public class PrintOtherOrderClosing extends PrinterRoot {
@Override @Override
public Map<String, List<Bitmap>> getPrintBitmap(Context mContext) { public Map<String, List<Bitmap>> getPrintBitmap(Context mContext, PrinterDeviceBean deviceBean) {
OrderDetails.DataBean dataBean = MyOrderManage.getDataBean(); OrderDetails.DataBean dataBean = MyOrderManage.getDataBean();
if (dataBean != null) { if (dataBean != null) {
Map<String, List<Bitmap>> bitmapMaps = new HashMap<>(); Map<String, List<Bitmap>> bitmapMaps = new HashMap<>();
......
...@@ -12,6 +12,7 @@ import androidx.recyclerview.widget.RecyclerView; ...@@ -12,6 +12,7 @@ import androidx.recyclerview.widget.RecyclerView;
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication; import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.utils.other.TextUtil; import com.gingersoft.gsa.cloud.base.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils; import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean;
import com.joe.print.R; import com.joe.print.R;
import com.joe.print.mvp.model.bean.PrjBean; import com.joe.print.mvp.model.bean.PrjBean;
import com.joe.print.mvp.ui.adapter.KitChenPrjPrintFoodAdapter; import com.joe.print.mvp.ui.adapter.KitChenPrjPrintFoodAdapter;
...@@ -29,7 +30,7 @@ public class PrintPrjKitchen extends PrinterRoot { ...@@ -29,7 +30,7 @@ public class PrintPrjKitchen extends PrinterRoot {
private static Map<String, List<PrjBean.DataBean.Bean>> prjMap; private static Map<String, List<PrjBean.DataBean.Bean>> prjMap;
@Override @Override
public Map<String, List<Bitmap>> getPrintBitmap(Context mContext) { public Map<String, List<Bitmap>> getPrintBitmap(Context mContext, PrinterDeviceBean deviceBean) {
Map<String, List<Bitmap>> bitmapMaps = new HashMap<>(); Map<String, List<Bitmap>> bitmapMaps = new HashMap<>();
//通過打印位置生成多張用於打印的bitmap //通過打印位置生成多張用於打印的bitmap
for (Map.Entry<String, List<PrjBean.DataBean.Bean>> entry : getPrjMap().entrySet()) { for (Map.Entry<String, List<PrjBean.DataBean.Bean>> entry : getPrjMap().entrySet()) {
......
...@@ -19,6 +19,7 @@ import com.gingersoft.gsa.cloud.base.common.bean.mealManage.MyOrderManage; ...@@ -19,6 +19,7 @@ import com.gingersoft.gsa.cloud.base.common.bean.mealManage.MyOrderManage;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.OpenTableManage; import com.gingersoft.gsa.cloud.base.common.bean.mealManage.OpenTableManage;
import com.gingersoft.gsa.cloud.base.utils.MoneyUtil; import com.gingersoft.gsa.cloud.base.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils; import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean;
import com.joe.print.R; import com.joe.print.R;
import java.math.BigDecimal; import java.math.BigDecimal;
...@@ -33,7 +34,7 @@ import java.util.Map; ...@@ -33,7 +34,7 @@ import java.util.Map;
public class PrintServe extends PrinterRoot { public class PrintServe extends PrinterRoot {
@Override @Override
public Map<String, List<Bitmap>> getPrintBitmap(Context mContext) { public Map<String, List<Bitmap>> getPrintBitmap(Context mContext, PrinterDeviceBean deviceBean) {
Map<String, List<Bitmap>> bitmapMaps = new HashMap<>(); Map<String, List<Bitmap>> bitmapMaps = new HashMap<>();
List<Bitmap> bitmaps = new ArrayList<>(); List<Bitmap> bitmaps = new ArrayList<>();
bitmaps.add(getServeBitmap(mContext)); bitmaps.add(getServeBitmap(mContext));
......
...@@ -21,6 +21,7 @@ import com.gingersoft.gsa.cloud.base.common.bean.mealManage.OpenTableManage; ...@@ -21,6 +21,7 @@ import com.gingersoft.gsa.cloud.base.common.bean.mealManage.OpenTableManage;
import com.gingersoft.gsa.cloud.base.utils.MoneyUtil; import com.gingersoft.gsa.cloud.base.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils; import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.constans.AppConstans; import com.gingersoft.gsa.cloud.constans.AppConstans;
import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean;
import com.joe.print.R; import com.joe.print.R;
import java.math.BigDecimal; import java.math.BigDecimal;
...@@ -36,12 +37,12 @@ import java.util.Map; ...@@ -36,12 +37,12 @@ import java.util.Map;
public class PrintSlip extends PrinterRoot { public class PrintSlip extends PrinterRoot {
@Override @Override
public Map<String, List<Bitmap>> getPrintBitmap(Context mContext) { public Map<String, List<Bitmap>> getPrintBitmap(Context mContext, PrinterDeviceBean deviceBean) {
List<Bitmap> bitmaps = new ArrayList<>(); List<Bitmap> bitmaps = new ArrayList<>();
bitmaps.add(getServeBitmap(mContext)); bitmaps.add(getServeBitmap(mContext));
//這裡可能還需要加上廚房單的內容,有未送單的食品時。 //這裡可能還需要加上廚房單的內容,有未送單的食品時。
PrintKitchen kitchen = new PrintKitchen(); PrintKitchen kitchen = new PrintKitchen();
Map<String, List<Bitmap>> bitmapMaps = new HashMap<>(kitchen.getPrintBitmap(mContext)); Map<String, List<Bitmap>> bitmapMaps = new HashMap<>(kitchen.getPrintBitmap(mContext, deviceBean));
if (bitmapMaps.size() == 0) { if (bitmapMaps.size() == 0) {
bitmapMaps.put("", bitmaps); bitmapMaps.put("", bitmaps);
} else { } else {
...@@ -92,7 +93,7 @@ public class PrintSlip extends PrinterRoot { ...@@ -92,7 +93,7 @@ public class PrintSlip extends PrinterRoot {
List<BillingBean> billingBeans = new ArrayList<>(); List<BillingBean> billingBeans = new ArrayList<>();
//添加合計項 //添加合計項
billingBeans.add(new BillingBean("合計",MyOrderManage.getInstance().getWholeAmount())); billingBeans.add(new BillingBean("合計", MyOrderManage.getInstance().getWholeAmount()));
//添加其他金額項 //添加其他金額項
if (MyOrderManage.getInstance().getOrderMoneyList().size() > 0) { if (MyOrderManage.getInstance().getOrderMoneyList().size() > 0) {
for (BillOrderMoney item : MyOrderManage.getInstance().getOrderMoneyList()) { for (BillOrderMoney item : MyOrderManage.getInstance().getOrderMoneyList()) {
......
...@@ -7,6 +7,7 @@ import android.widget.LinearLayout; ...@@ -7,6 +7,7 @@ import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils; import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean;
import com.joe.print.R; import com.joe.print.R;
import java.util.ArrayList; import java.util.ArrayList;
...@@ -21,7 +22,7 @@ public class PrintTest extends PrinterRoot { ...@@ -21,7 +22,7 @@ public class PrintTest extends PrinterRoot {
@Override @Override
public Map<String, List<Bitmap>> getPrintBitmap(Context mContext) { public Map<String, List<Bitmap>> getPrintBitmap(Context mContext, PrinterDeviceBean deviceBean) {
Map<String, List<Bitmap>> bitmapMaps = new HashMap<>(); Map<String, List<Bitmap>> bitmapMaps = new HashMap<>();
List<Bitmap> bitmaps = new ArrayList<>(); List<Bitmap> bitmaps = new ArrayList<>();
bitmaps.add(getTestPrintBitmap(mContext)); bitmaps.add(getTestPrintBitmap(mContext));
...@@ -41,7 +42,7 @@ public class PrintTest extends PrinterRoot { ...@@ -41,7 +42,7 @@ public class PrintTest extends PrinterRoot {
* @param context * @param context
* @return * @return
*/ */
private Bitmap getTestPrintBitmap(Context context) { public Bitmap getTestPrintBitmap(Context context) {
View view = LinearLayout.inflate(context, R.layout.print_test, null); View view = LinearLayout.inflate(context, R.layout.print_test, null);
TextView tvTime = view.findViewById(R.id.tv_test_print_now_time); TextView tvTime = view.findViewById(R.id.tv_test_print_now_time);
tvTime.setText("時間:" + TimeUtils.getCurrentDate(TimeUtils.DEFAULT_DATE_FORMAT)); tvTime.setText("時間:" + TimeUtils.getCurrentDate(TimeUtils.DEFAULT_DATE_FORMAT));
......
...@@ -7,7 +7,9 @@ import android.os.Build; ...@@ -7,7 +7,9 @@ import android.os.Build;
import android.os.IBinder; import android.os.IBinder;
import android.os.RemoteException; import android.os.RemoteException;
import android.util.Log; import android.util.Log;
import android.view.Gravity;
import android.view.View; import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
import androidx.core.content.ContextCompat; import androidx.core.content.ContextCompat;
...@@ -17,7 +19,14 @@ import androidx.recyclerview.widget.RecyclerView; ...@@ -17,7 +19,14 @@ import androidx.recyclerview.widget.RecyclerView;
import com.epson.epos2.printer.Printer; import com.epson.epos2.printer.Printer;
import com.epson.epos2.printer.PrinterStatusInfo; import com.epson.epos2.printer.PrinterStatusInfo;
import com.epson.epos2.printer.ReceiveListener; import com.epson.epos2.printer.ReceiveListener;
import com.gingersoft.gsa.cloud.base.adapter.print.BillAdapter;
import com.gingersoft.gsa.cloud.base.adapter.print.BillTypeAdapter;
import com.gingersoft.gsa.cloud.base.adapter.print.FoodAdapter;
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication; import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.common.bean.BillingBean;
import com.gingersoft.gsa.cloud.base.common.bean.OrderDetail;
import com.gingersoft.gsa.cloud.base.common.bean.PayMethod;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.MyOrderManage;
import com.gingersoft.gsa.cloud.base.utils.AidlUtil; import com.gingersoft.gsa.cloud.base.utils.AidlUtil;
import com.gingersoft.gsa.cloud.base.utils.other.SPUtils; import com.gingersoft.gsa.cloud.base.utils.other.SPUtils;
import com.gingersoft.gsa.cloud.base.utils.toast.ToastUtils; import com.gingersoft.gsa.cloud.base.utils.toast.ToastUtils;
...@@ -28,11 +37,18 @@ import com.gingersoft.gsa.cloud.constans.PrintConstans; ...@@ -28,11 +37,18 @@ import com.gingersoft.gsa.cloud.constans.PrintConstans;
import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean; import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean;
import com.gingersoft.gsa.cloud.print.PrintExecutor; import com.gingersoft.gsa.cloud.print.PrintExecutor;
import com.gingersoft.gsa.cloud.print.PrintSocketHolder; import com.gingersoft.gsa.cloud.print.PrintSocketHolder;
import com.gingersoft.gsa.cloud.print.PrinterWriter;
import com.hyweb.n5.lib.constant.PrinterConstant; import com.hyweb.n5.lib.constant.PrinterConstant;
import com.hyweb.n5.lib.util.PrinterUtil; import com.hyweb.n5.lib.util.PrinterUtil;
import com.hyweb.n5.server.aidl.IOnPrintCallback; import com.hyweb.n5.server.aidl.IOnPrintCallback;
import com.jess.arms.utils.ArmsUtils; import com.jess.arms.utils.ArmsUtils;
import com.joe.print.R; import com.joe.print.R;
import com.joe.print.mvp.print.common.PrinterFinderCallback;
import com.joe.print.mvp.print.common.SendResultCode;
import com.joe.print.mvp.print.usb.EscCommand;
import com.joe.print.mvp.print.usb.UsbPrint;
import com.joe.print.mvp.print.usb.UsbPrinter;
import com.joe.print.mvp.print.usb.UsbPrinterFinder;
import com.joe.print.mvp.ui.activity.PrintActivity; import com.joe.print.mvp.ui.activity.PrintActivity;
import com.joe.print.mvp.ui.adapter.DialogPrinterListAdapter; import com.joe.print.mvp.ui.adapter.DialogPrinterListAdapter;
import com.sunmi.peripheral.printer.InnerResultCallbcak; import com.sunmi.peripheral.printer.InnerResultCallbcak;
...@@ -133,8 +149,14 @@ public abstract class PrinterRoot implements PrintSocketHolder.OnStateChangedLis ...@@ -133,8 +149,14 @@ public abstract class PrinterRoot implements PrintSocketHolder.OnStateChangedLis
* @param mContext * @param mContext
* @return key為打印位置,值為圖片集合的map * @return key為打印位置,值為圖片集合的map
*/ */
public abstract Map<String, List<Bitmap>> getPrintBitmap(Context mContext); public abstract Map<String, List<Bitmap>> getPrintBitmap(Context mContext, PrinterDeviceBean deviceBean);
/**
* 獲取打印次數
*
* @param context
* @return
*/
public abstract int getPrintCount(Context context); public abstract int getPrintCount(Context context);
public void print(List<PrinterDeviceBean> deviceBeans) { public void print(List<PrinterDeviceBean> deviceBeans) {
...@@ -143,7 +165,7 @@ public abstract class PrinterRoot implements PrintSocketHolder.OnStateChangedLis ...@@ -143,7 +165,7 @@ public abstract class PrinterRoot implements PrintSocketHolder.OnStateChangedLis
PrintExecutor executor = new PrintExecutor(getDefaultPrintInList(deviceBeans)); PrintExecutor executor = new PrintExecutor(getDefaultPrintInList(deviceBeans));
executor.doPrinterRequestAsync(new OpenCashBoxMaker()); executor.doPrinterRequestAsync(new OpenCashBoxMaker());
} else { } else {
listMap = getPrintBitmap(mContext); // listMap = getPrintBitmap(mContext);
if (listMap == null) { if (listMap == null) {
printListener.printFile(); printListener.printFile();
return; return;
...@@ -169,7 +191,6 @@ public abstract class PrinterRoot implements PrintSocketHolder.OnStateChangedLis ...@@ -169,7 +191,6 @@ public abstract class PrinterRoot implements PrintSocketHolder.OnStateChangedLis
} }
} }
/** /**
* 本機打印 * 本機打印
*/ */
...@@ -487,6 +508,18 @@ public abstract class PrinterRoot implements PrintSocketHolder.OnStateChangedLis ...@@ -487,6 +508,18 @@ public abstract class PrinterRoot implements PrintSocketHolder.OnStateChangedLis
ipDevicePrint(printerDeviceBean, bitmaps, this, this); ipDevicePrint(printerDeviceBean, bitmaps, this, this);
} }
protected Bitmap zoomBitmap(PrinterDeviceBean printerDeviceBean, Bitmap bitmap) {
int printWidth;
if (printerDeviceBean != null && printerDeviceBean.getPaperSpecification() != null) {
printWidth = Double.valueOf(printerDeviceBean.getPaperSpecification()).intValue();
} else {
//如果打印機沒設置寬度
printWidth = 480;
}
return ImageUtils.zoomDrawable(bitmap, printWidth);
}
private EpsonPrint mPrinter; private EpsonPrint mPrinter;
/** /**
...@@ -495,7 +528,6 @@ public abstract class PrinterRoot implements PrintSocketHolder.OnStateChangedLis ...@@ -495,7 +528,6 @@ public abstract class PrinterRoot implements PrintSocketHolder.OnStateChangedLis
public void ipDevicePrint(PrinterDeviceBean public void ipDevicePrint(PrinterDeviceBean
printerDeviceBean, List<Bitmap> bitmaps, PrintSocketHolder.OnStateChangedListener printerDeviceBean, List<Bitmap> bitmaps, PrintSocketHolder.OnStateChangedListener
stateChangedListener, PrintExecutor.OnPrintResultListener resultListener) { stateChangedListener, PrintExecutor.OnPrintResultListener resultListener) {
if (printerDeviceBean == null) if (printerDeviceBean == null)
return; return;
int printWidth;//打印出來的內容寬度 int printWidth;//打印出來的內容寬度
...@@ -563,6 +595,47 @@ public abstract class PrinterRoot implements PrintSocketHolder.OnStateChangedLis ...@@ -563,6 +595,47 @@ public abstract class PrinterRoot implements PrintSocketHolder.OnStateChangedLis
} }
} }
public void usbPrint(Context context, List<Bitmap> bitmaps) {
UsbPrint usbPrint = UsbPrint.getInstance(context, (code, printId) -> {
//打印結果
if (code == SendResultCode.SEND_SUCCESS) {
Log.e("eee", "打印成功");
} else if (code == SendResultCode.SEND_FAILED) {
Log.e("eee", "打印失敗");
}
});
//查找打印機
UsbPrinterFinder printerFinder = new UsbPrinterFinder(context, new PrinterFinderCallback<UsbPrinter>() {
@Override
public void onStart() {
ToastUtils.show(context, "開始尋找打印機");
}
@Override
public void onFound(UsbPrinter usbPrinter) {
}
@Override
public void onFinished(List<UsbPrinter> usbPrinters) {
if (usbPrinters != null && usbPrinters.size() > 0) {
for (Bitmap bitmap : bitmaps) {
EscCommand esc = new EscCommand();
byte[] bytes = PrinterWriter.decodeBitmapToDataList(bitmap, 255);
if (bytes != null) {
esc.addArrayToCommand(bytes);
}
esc.addCutPaper();
esc.addCleanCache();
usbPrint.sendPrintCommand(usbPrinters.get(0), esc.getByteArrayCommand());
}
} else {
ToastUtils.show(context, "未找到USB打印機");
}
}
});
printerFinder.startFinder();
}
/** /**
* view轉bitmap * view轉bitmap
* *
...@@ -728,4 +801,83 @@ public abstract class PrinterRoot implements PrintSocketHolder.OnStateChangedLis ...@@ -728,4 +801,83 @@ public abstract class PrinterRoot implements PrintSocketHolder.OnStateChangedLis
// EpsonPrint.getInstance().disconnectPrinter(); // EpsonPrint.getInstance().disconnectPrinter();
// EpsonPrint.getInstance().finalizeObject(); // EpsonPrint.getInstance().finalizeObject();
} }
public View getLine(Context mContext) {
TextView textView = new TextView(mContext);
textView.setMaxLines(1);
textView.setText(mContext.getString(R.string.print_split_line));
return textView;
}
public View getHalfLine(Context mContext) {
return View.inflate(mContext, R.layout.print_model_half_line, null);
}
public View getHeader(Context mContext) {
View view = View.inflate(mContext, R.layout.print_model_header, null);
TextView tvBrandName = view.findViewById(R.id.print_brand_name);
TextView tvRestaurantName = view.findViewById(R.id.print_restaurant_name);
tvBrandName.setText(GsaCloudApplication.getBrandName(mContext));
tvRestaurantName.setText(GsaCloudApplication.getRestaurantName(mContext));
return view;
}
public View getDiningTableOrderInfo(Context mContext, String diningTable, String people, String orderNum, String createTime) {
View view = View.inflate(mContext, R.layout.print_model_dining_table_order_info, null);
TextView tvDiningTable = view.findViewById(R.id.tv_print_model_dining_table);
TextView tvPeople = view.findViewById(R.id.tv_print_model_people);
TextView tvOrderNum = view.findViewById(R.id.tv_print_model_order_number);
TextView tvCreateTime = view.findViewById(R.id.tv_print_model_data);
tvDiningTable.setVisibility(diningTable == null ? View.GONE : View.VISIBLE);
tvPeople.setVisibility(people == null ? View.GONE : View.VISIBLE);
tvOrderNum.setVisibility(orderNum == null ? View.GONE : View.VISIBLE);
tvCreateTime.setVisibility(createTime == null ? View.GONE : View.VISIBLE);
tvDiningTable.setText(diningTable);
tvPeople.setText(people);
tvOrderNum.setText(orderNum);
tvCreateTime.setText(createTime);
return view;
}
public View getDiningFoodList(Context mContext, List<OrderDetail> foodList) {
RecyclerView recyclerView = new RecyclerView(mContext);
FoodAdapter foodAdapter = new FoodAdapter(foodList);
recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
recyclerView.setAdapter(foodAdapter);
return recyclerView;
}
public View getDiningBillInfo(Context mContext, List<BillingBean> billingBeans) {
RecyclerView rvBillAmount = new RecyclerView(mContext);
BillAdapter billAdapter = new BillAdapter(billingBeans);
rvBillAmount.setLayoutManager(new LinearLayoutManager(mContext));
rvBillAmount.setAdapter(billAdapter);
return rvBillAmount;
}
public View getDiningBillPayMethod(Context mContext, List<PayMethod> payBillMoneys) {
RecyclerView rvPayType = new RecyclerView(mContext);
rvPayType.setLayoutManager(new LinearLayoutManager(mContext));
rvPayType.setAdapter(new BillTypeAdapter(payBillMoneys));
return rvPayType;
}
public View getAmountText(Context mContext,String text){
return getTextView(mContext, text, Gravity.RIGHT, mContext.getResources().getDimensionPixelSize(R.dimen.dp_24), ContextCompat.getColor(mContext, R.color.black));
}
public View getTextView(Context mContext, String text, int gravity, int textSize, int textColor) {
TextView textView = new TextView(mContext);
textView.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
textView.setText(text);
textView.setTextColor(textColor);
textView.setTextSize(textSize);
textView.setGravity(gravity);
return textView;
}
} }
package com.joe.print.mvp.print.bluetooth;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;
import com.joe.print.mvp.print.common.SendCallback;
import com.joe.print.mvp.print.common.SendResultCode;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class BluetoothPrint {
private static final String TAG = "BluetoothPrint";
private static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
private static BluetoothPrint INSTANCE;
private SendCallback sendCallback;
private UUID uuid;
private MyHandler myHandler;
private final ExecutorService threadPool;
private BluetoothPrint(SendCallback sendCallback) {
this.uuid = UUID.fromString(SPP_UUID);
this.myHandler = new MyHandler(this);
this.sendCallback = sendCallback;
this.threadPool = Executors.newFixedThreadPool(3);
}
public static BluetoothPrint getInstance(SendCallback sendCallback) {
if (INSTANCE == null) {
synchronized (BluetoothPrint.class) {
if (INSTANCE == null) {
INSTANCE = new BluetoothPrint(sendCallback);
}
}
}
return INSTANCE;
}
public void sendPrintCommand(BluetoothDevice device, byte[] bytes) {
SendCommandThread thread = new SendCommandThread(device, bytes);
threadPool.execute(thread);
}
private class SendCommandThread extends Thread {
private BluetoothDevice device;
private byte[] bytes;
private BluetoothSocket socket;
public SendCommandThread(BluetoothDevice device, byte[] bytes) {
this.device = device;
this.bytes = bytes;
}
@Override
public void run() {
try {
socket = device.createRfcommSocketToServiceRecord(uuid);
socket.connect();
OutputStream os = socket.getOutputStream();
os.write(bytes);
os.flush();
os.close();
sendStatus(device.getName(), SendResultCode.SEND_SUCCESS);
} catch (IOException e) {
e.printStackTrace();
sendStatus(device.getName(), SendResultCode.SEND_FAILED);
}
}
}
private void sendStatus(String ip, int code) {
Message msg = Message.obtain();
msg.what = code;
msg.obj = ip;
myHandler.sendMessage(msg);
}
private static class MyHandler extends Handler {
private WeakReference<BluetoothPrint> reference;
public MyHandler(BluetoothPrint manager) {
this.reference = new WeakReference<>(manager);
}
@Override
public void handleMessage(Message msg) {
BluetoothPrint manager = reference.get();
if (manager != null) {
manager.sendCallback.onCallback(msg.what, (String) msg.obj);
}
}
}
}
package com.joe.print.mvp.print.serial;
public interface ReadCallback {
void onReading(String s);
}
package com.joe.print.mvp.print.serial;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.joe.print.mvp.print.serial.utils.SerialPort;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.security.InvalidParameterException;
import java.util.Arrays;
public class SerialPortRead {
private SerialPort serialPort;
private InputStream is;
private boolean isReading = false;
private ReadCallback callback;
private MyHandler myHandler;
public void open(String path, int baudRate, ReadCallback callback) {
try {
this.myHandler = new MyHandler(this);
this.callback = callback;
this.isReading = true;
this.serialPort = new SerialPort(new File(path), baudRate, 0);
this.is = serialPort.getInputStream();
new ReadThread(is).start();
} catch (SecurityException e) {
callback.onReading("SecurityException");
//DisplayError(R.string.error_security);
} catch (IOException e) {
callback.onReading("IOException");
//DisplayError(R.string.error_unknown);
} catch (InvalidParameterException e) {
callback.onReading("InvalidParameterException");
//DisplayError(R.string.error_configuration);
}
}
private class ReadThread extends Thread {
private InputStream is;
public ReadThread(InputStream is) {
this.is = is;
}
@Override
public void run() {
while (isReading) {
long id = Thread.currentThread().getId();
Log.d("thread", "id =" + id);
try {
if (is == null) return;
String s;
byte[] line = readLine(is);
if (line[0] == 87) {
s = readWENTEC(line);
} else {
s = readDaHua(line);
}
sendMessage(s);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private String readDaHua(byte[] line) {
try {
String s = ASCII2HexString(line, 22).substring(0, 5).trim();
double b = Double.parseDouble(s) / 1000;
return String.valueOf(b);
} catch (NumberFormatException e) {
e.printStackTrace();
}
return "0.000";
}
private byte[] readLine(InputStream is) throws IOException {
//5518 000 000\n\r
//WGT:1 5.570P 0.000\r\n
byte[] line = new byte[22];
byte[] buffer = new byte[2];
int index = 0;
byte[] _r = new byte[1];//13
byte[] _n = new byte[1];//10
for (; ; ) {
if (is.read(buffer, 0, 1) != -1) {
line[index] = buffer[0];
index++;
if (buffer[0] == 13) {
_r[0] = buffer[0];
}
if (buffer[0] == 10) {
_n[0] = buffer[0];
}
boolean isEnd = _r[0] == 13 && _n[0] == 10;
if (index >= 22 || isEnd) {
break;
}
} else {
break;
}
}
Log.d("byteline", Arrays.toString(line));
return line;
}
private String readWENTEC(byte[] line) throws IOException {
Log.d("line=", Arrays.toString(line));
byte[] buf = new byte[20];
if (line[0] == 'W') {
byte status = line[4];
byte[] net_weight = new byte[7];
byte sep = 'P';
byte[] tare_weight = new byte[7];
System.arraycopy(line, 5, net_weight, 0, 6);
System.arraycopy(line, 12, tare_weight, 0, 6);
buf[0] = status;
for (int i = 0; i < 6; i++) {
buf[i + 1] = net_weight[i];
}
buf[7] = sep;
for (int j = 0; j < 6; j++) {
buf[j + 8] = tare_weight[j];
}
}
Log.d("WINTEC:", ASCII2HexString(line, line.length));
String a = ASCII2HexString(buf, 20).substring(0, 1);
String b = ASCII2HexString(buf, 20).substring(1, 7);
String c = ASCII2HexString(buf, 20).substring(8, 14);
Log.d("WINTEC:", "a=" + a + ", b=" + b + ", c=" + c);
return b;
}
public String ASCII2HexString(byte[] src, int n) {
char[] data = new char[n];
for (int i = 0; i < src.length; i++) {
data[i] = (char) ((int) (src[i]));
}
return new String(data);
}
private static class MyHandler extends Handler {
private WeakReference<SerialPortRead> weakReference;
public MyHandler(SerialPortRead read) {
this.weakReference = new WeakReference<>(read);
}
@Override
public void handleMessage(Message msg) {
SerialPortRead read = weakReference.get();
if (read != null && read.callback != null) {
read.callback.onReading((String) msg.obj);
}
}
}
private void sendMessage(String s) {
if (myHandler == null) return;
Message msg = new Message();
msg.obj = s;
myHandler.sendMessage(msg);
}
public void close() {
isReading = false;
try {
if (is != null) {
is.close();
}
if (serialPort != null) {
serialPort.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.joe.print.mvp.print.serial;
import com.joe.print.mvp.print.serial.utils.SerialPort;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidParameterException;
public class SerialPortWrite {
private SerialPort serialPort;
private OutputStream os;
public void open(String path, int baudRate) {
try {
serialPort = new SerialPort(new File(path), baudRate, 0);
os = serialPort.getOutputStream();
} catch (SecurityException e) {
//DisplayError(R.string.error_security);
} catch (IOException e) {
//DisplayError(R.string.error_unknown);
} catch (InvalidParameterException e) {
//DisplayError(R.string.error_configuration);
}
}
// public void write(String price, WriteType type) {
// try {
// if (os == null) return;
// int[] command = getCommand(price, type);
// byte[] bytes = new byte[command.length];
// for (int i = 0; i < command.length; i++) {
// bytes[i] = (byte) command[i];
// }
// os.write(bytes);
// os.flush();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
public void close() {
try {
if (os != null) {
os.close();
}
if (serialPort != null) {
serialPort.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// private int[] getCommand(String price, WriteType type) {
// List<Integer> commands = new ArrayList<>();
// //找零
// if (type == TYPE_CHARGE) {
// commands.add(0X1B);
// commands.add(0X73);
// commands.add(0X34);
// commands.add(0X1B);
// commands.add(0X51);
// commands.add(0X41);
// //总计
// } else if (type == TYPE_TOTAL) {
// commands.add(0X1B);
// commands.add(0X73);
// commands.add(0X32);
// commands.add(0X1B);
// commands.add(0X51);
// commands.add(0X41);
// //全暗
// } else if (type == TYPE_CLEAR) {
// commands.add(0X1B);
// commands.add(0X73);
// commands.add(0X30);
// commands.add(0X1B);
// commands.add(0X51);
// commands.add(0X41);
// for (int i = 0; i < 7; i++) {
// commands.add(0X20);
// }
// commands.add(0x0D);
// int[] intArray = new int[commands.size()];
// for (int i = 0; i < intArray.length; i++) {
// intArray[i] = commands.get(i);
// }
//
// return intArray;
// }
//
// String str = price;
// for (int i = 0; i < str.length(); i++) {
// String temp = str.substring(i, i + 1);
// if (temp.equals(".")) {
// commands.add(0X2E);
// }
// if (temp.equals("0")) {
// commands.add(0X30);
// }
// if (temp.equals("1")) {
// commands.add(0X31);
// }
// if (temp.equals("2")) {
// commands.add(0X32);
// }
// if (temp.equals("3")) {
// commands.add(0X33);
// }
// if (temp.equals("4")) {
// commands.add(0X34);
// }
// if (temp.equals("5")) {
// commands.add(0X35);
// }
// if (temp.equals("6")) {
// commands.add(0X36);
// }
// if (temp.equals("7")) {
// commands.add(0X37);
// }
// if (temp.equals("8")) {
// commands.add(0X38);
// }
// if (temp.equals("9")) {
// commands.add(0X39);
// }
//
// }
// for (int i = 0; i < 8 - str.length(); i++) {
// commands.add(0X20);
// }
// commands.add(0X0D);
//
// int[] intArray = new int[commands.size()];
// for (int i = 0; i < intArray.length; i++) {
// intArray[i] = commands.get(i);
// }
//
// return intArray;
// }
public enum WriteType {
TYPE_CHARGE,
TYPE_TOTAL,
TYPE_CLEAR,
}
}
/*
* Copyright 2009 Cedric Priscal
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.joe.print.mvp.print.serial.utils;
import android.util.Log;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class SerialPort {
private static final String TAG = "SerialPort";
/*
* Do not remove or rename the field mFd: it is used by native method close();
*/
private FileDescriptor mFd;
private FileInputStream mFileInputStream;
private FileOutputStream mFileOutputStream;
public SerialPort(File device, int baudrate, int flags) throws SecurityException, IOException {
/* Check access permission */
if (!device.canRead() || !device.canWrite()) {
try {
/* Missing read/write permission, trying to chmod the file */
Process su;
su = Runtime.getRuntime().exec("/system/bin/su");
String cmd = "chmod 666 " + device.getAbsolutePath() + "\n"
+ "exit\n";
su.getOutputStream().write(cmd.getBytes());
if ((su.waitFor() != 0) || !device.canRead()
|| !device.canWrite()) {
throw new SecurityException();
}
} catch (Exception e) {
e.printStackTrace();
throw new SecurityException();
}
}
mFd = open(device.getAbsolutePath(), baudrate, flags);
if (mFd == null) {
Log.e(TAG, "native open returns null");
throw new IOException();
}
mFileInputStream = new FileInputStream(mFd);
mFileOutputStream = new FileOutputStream(mFd);
}
// Getters and setters
public InputStream getInputStream() {
return mFileInputStream;
}
public OutputStream getOutputStream() {
return mFileOutputStream;
}
// JNI
private native static FileDescriptor open(String path, int baudrate, int flags);
public native void close();
static {
System.loadLibrary("serial_port");
}
}
...@@ -8,6 +8,9 @@ import android.util.Log; ...@@ -8,6 +8,9 @@ import android.util.Log;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import com.epson.epos2.printer.Printer;
import com.epson.epos2.printer.PrinterStatusInfo;
import com.epson.epos2.printer.ReceiveListener;
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication; import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.utils.JsonUtils; import com.gingersoft.gsa.cloud.base.utils.JsonUtils;
import com.gingersoft.gsa.cloud.base.utils.okhttpUtils.OkHttp3Utils; import com.gingersoft.gsa.cloud.base.utils.okhttpUtils.OkHttp3Utils;
...@@ -49,22 +52,14 @@ import static com.joe.print.mvp.print.PrinterRoot.PRINT_KITCHEN; ...@@ -49,22 +52,14 @@ import static com.joe.print.mvp.print.PrinterRoot.PRINT_KITCHEN;
/** /**
* 在用戶登錄成功後,打開打印service,每隔3~5秒請求一次。請求到了數據就進行打印邏輯 * 在用戶登錄成功後,打開打印service,每隔3~5秒請求一次。請求到了數據就進行打印邏輯
*/ */
public class PrjService extends Service implements PrintSocketHolder.OnStateChangedListener, PrintExecutor.OnPrintResultListener { public class PrjService extends Service implements PrintSocketHolder.OnStateChangedListener, PrintExecutor.OnPrintResultListener, ReceiveListener {
private Disposable disposable; private Disposable disposable;
private Disposable wakeDisposable; private Disposable wakeDisposable;
private List<PrinterDeviceBean> printerDeviceBeans; private List<PrinterDeviceBean> printerDeviceBeans;
private List<PrjBean.DataBean.Bean> printDatas = new ArrayList<>(); private List<PrjBean.DataBean.Bean> printDatas = new ArrayList<>();
private Map<String, List<PrjBean.DataBean.Bean>> listMap = new HashMap<>();
private List<PrintCurrencyBean> printCurrencyBeans;//通用打印配置 private List<PrintCurrencyBean> printCurrencyBeans;//通用打印配置
// @Override
// public void onCreate() {
// super.onCreate();
// //讀取本地ip打印機
// Log.e("eee", "開啟打印服務");
// getPrintList();
// //開始請求
// startGetPrjInfo();
// }
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(Intent intent, int flags, int startId) {
...@@ -94,9 +89,9 @@ public class PrjService extends Service implements PrintSocketHolder.OnStateChan ...@@ -94,9 +89,9 @@ public class PrjService extends Service implements PrintSocketHolder.OnStateChan
* 開啟輪詢查詢prj數據 * 開啟輪詢查詢prj數據
*/ */
private void startGetPrjInfo() { private void startGetPrjInfo() {
if (wakeDisposable != null && !wakeDisposable.isDisposed()) { cancel(wakeDisposable);
wakeDisposable.dispose(); cancel(disposable);
}
Observable.interval(10, 30, TimeUnit.SECONDS) Observable.interval(10, 30, TimeUnit.SECONDS)
.subscribe(new Observer<Long>() { .subscribe(new Observer<Long>() {
@Override @Override
...@@ -107,7 +102,6 @@ public class PrjService extends Service implements PrintSocketHolder.OnStateChan ...@@ -107,7 +102,6 @@ public class PrjService extends Service implements PrintSocketHolder.OnStateChan
@Override @Override
public void onNext(Long aLong) { public void onNext(Long aLong) {
getPrjInfo(); getPrjInfo();
cancel();
} }
@Override @Override
...@@ -142,10 +136,8 @@ public class PrjService extends Service implements PrintSocketHolder.OnStateChan ...@@ -142,10 +136,8 @@ public class PrjService extends Service implements PrintSocketHolder.OnStateChan
//請求到數據,停止輪詢,開始打印,在打印完之後再重新開始輪詢 //請求到數據,停止輪詢,開始打印,在打印完之後再重新開始輪詢
startPrint(s); startPrint(s);
//開啟另一個定時,三十秒之後自動請求,避免上面的打印成功或失敗時沒有回調。 //開啟另一個定時,三十秒之後自動請求,避免上面的打印成功或失敗時沒有回調。
if (wakeDisposable != null) { cancel(wakeDisposable);
wakeDisposable.dispose(); Observable.timer(30, TimeUnit.SECONDS)
}
Observable.timer(10, TimeUnit.SECONDS)
.subscribe(new Observer<Long>() { .subscribe(new Observer<Long>() {
@Override @Override
public void onSubscribe(Disposable d) { public void onSubscribe(Disposable d) {
...@@ -183,7 +175,7 @@ public class PrjService extends Service implements PrintSocketHolder.OnStateChan ...@@ -183,7 +175,7 @@ public class PrjService extends Service implements PrintSocketHolder.OnStateChan
/** /**
* 取消輪詢 * 取消輪詢
*/ */
private void cancel() { private void cancel(Disposable disposable) {
if (disposable != null) { if (disposable != null) {
disposable.dispose(); disposable.dispose();
} }
...@@ -191,20 +183,21 @@ public class PrjService extends Service implements PrintSocketHolder.OnStateChan ...@@ -191,20 +183,21 @@ public class PrjService extends Service implements PrintSocketHolder.OnStateChan
private PrinterRoot printerInIt; private PrinterRoot printerInIt;
private String json = "{\"success\":true,\"sysTime\":1595066909048,\"data\":{\"K1\":[{\"id\":2461,\"printerDeviceId\":87,\"status\":1,\"orderNo\":\"153201882821850443\",\"orderTime\":2020,\"sender\":\"\",\"person\":0,\"number\":1,\"orderDetailsTime\":\"Jul 10, 2020 11:59:29 AM\",\"orderDetailsId\":48863119,\"productName\":\"紅棗銀耳湯\",\"parentId\":48863115,\"type\":4,\"createTime\":1595066908689,\"productId\":5189,\"requests\":1,\"actualPrinterDeviceId\":87,\"takeFoodCode\":\"H462\",\"billNo\":\"0643\",\"orderType\":7,\"userName\":\"stefan001\"}]}}\n"; private String json = "{\"success\":true,\"sysTime\":1595066909048,\"data\":{\"K1\":[{\"id\":2461,\"printerDeviceId\":87,\"status\":1,\"orderNo\":\"153201882821850443\",\"orderTime\":2020,\"sender\":\"\",\"person\":0,\"number\":1,\"orderDetailsTime\":\"Jul 10, 2020 11:59:29 AM\",\"orderDetailsId\":48863119,\"productName\":\"紅棗銀耳湯\",\"parentId\":48863115,\"type\":4,\"createTime\":1595066908689,\"productId\":5189,\"requests\":1,\"actualPrinterDeviceId\":87,\"takeFoodCode\":\"H462\",\"billNo\":\"0643\",\"orderType\":7,\"userName\":\"stefan001\"},{\"id\":2461,\"printerDeviceId\":87,\"status\":1,\"orderNo\":\"153201882821850443\",\"orderTime\":2020,\"sender\":\"\",\"person\":0,\"number\":1,\"orderDetailsTime\":\"Jul 10, 2020 11:59:29 AM\",\"orderDetailsId\":48863119,\"productName\":\"紅棗銀耳湯\",\"parentId\":48863115,\"type\":4,\"createTime\":1595066908689,\"productId\":5189,\"requests\":1,\"actualPrinterDeviceId\":87,\"takeFoodCode\":\"H462\",\"billNo\":\"0643\",\"orderType\":7,\"userName\":\"stefan001\"}]}}";
/** /**
* 開始打印 * 開始打印
*/ */
private void startPrint(String json) { private void startPrint(String json) {
printDatas.clear(); printDatas.clear();
PrintCurrencyBean printCurrencyBean; listMap.clear();
PrjBean prjBean = JsonUtils.parseObject(json, PrjBean.class); PrjBean prjBean = JsonUtils.parseObject(json, PrjBean.class);
if (prjBean == null || prjBean.getData() == null) { if (prjBean == null || prjBean.getData() == null) {
return; return;
} }
Map<String, List<PrjBean.DataBean.Bean>> listMap = new HashMap<>(); PrintCurrencyBean printCurrencyBean;
//有數據,取消輪詢,等待打印結束。
cancel(disposable);
try { try {
JSONObject jsonObject = new JSONObject(prjBean.getData()); JSONObject jsonObject = new JSONObject(prjBean.getData());
//通过迭代器获取这段json当中所有的key值 //通过迭代器获取这段json当中所有的key值
...@@ -230,46 +223,42 @@ public class PrjService extends Service implements PrintSocketHolder.OnStateChan ...@@ -230,46 +223,42 @@ public class PrjService extends Service implements PrintSocketHolder.OnStateChan
} }
//獲取打印機列表 //獲取打印機列表
getPrintList(); getPrintList();
for (Map.Entry<String, List<PrjBean.DataBean.Bean>> prjMap : listMap.entrySet()) { // for (Map.Entry<String, List<PrjBean.DataBean.Bean>> prjMap : listMap.entrySet()) {
for (PrinterDeviceBean deviceBean : printerDeviceBeans) { // for (PrinterDeviceBean deviceBean : printerDeviceBeans) {
if (prjMap.getKey().equalsIgnoreCase(deviceBean.getName())) { // if (prjMap.getKey().equalsIgnoreCase(deviceBean.getName())) {
if ((deviceBean.getPrinterName() != null && deviceBean.getPrinterName().toLowerCase().contains("EPSON".toLowerCase())) // if ((deviceBean.getPrinterName() != null && deviceBean.getPrinterName().toLowerCase().contains("EPSON".toLowerCase()))
&& (deviceBean.getModel() != null && deviceBean.getModel().toLowerCase().contains("TM-U220B".toLowerCase()))) { // && (deviceBean.getModel() != null && deviceBean.getModel().toLowerCase().contains("TM-U220B".toLowerCase()))) {
//針式打印 // //針式打印
//Epson打印機打印,調用對應的方法 // //Epson打印機打印,調用對應的方法
EpsonPrint mPrinter = EpsonPrint.getInstance(); // EpsonPrint mPrinter = EpsonPrint.getInstance();
// PrinterStatusInfo status = mPrinter.getStatus(); // mPrinter.initializeObject(GsaCloudApplication.getAppContext(), this);
// if (status != null && status.getPaper() == 2) { // int paperWidth = 42;
// ToastUtils.show(this, "打印機缺紙"); // if (deviceBean.getPaperSpecification() != null) {
// paperWidth = (int) (Double.parseDouble(deviceBean.getPaperSpecification()) / 6);
// } // }
mPrinter.initializeObject(GsaCloudApplication.getAppContext(), null); // List<List<PrintInfoBean>> prjBeans = PrintInfoBean.transPrjBean(prjMap.getValue(), prjMap.getKey(), deviceBean, printCurrencyBean);
int paperWidth = 42; // for (List<PrintInfoBean> prjPrintBean : prjBeans) {
if (deviceBean.getPaperSpecification() != null) { // mPrinter.putPrintString(deviceBean.getIp(), paperWidth, prjPrintBean);
paperWidth = (int) (Double.parseDouble(deviceBean.getPaperSpecification()) / 6); // }
} // }
List<List<PrintInfoBean>> prjBeans = PrintInfoBean.transPrjBean(prjMap.getValue(), paperWidth, prjMap.getKey(), deviceBean, printCurrencyBean); // }
for (List<PrintInfoBean> prjPrintBean : prjBeans) { // }
mPrinter.putPrintString(deviceBean.getIp(), paperWidth, prjPrintBean); // }
}
}
}
}
}
if (printerInIt != null) { if (printerInIt != null) {
printerInIt.setmContext(this); printerInIt.setmContext(this);
for (Map.Entry<String, List<Bitmap>> entry : printerInIt.getPrintBitmap(this).entrySet()) { for (Map.Entry<String, List<Bitmap>> entry : printerInIt.getPrintBitmap(this, null).entrySet()) {
//遍歷所有的需要打印的內容 //遍歷所有的需要打印的內容
for (PrinterDeviceBean deviceBean : printerDeviceBeans) { for (PrinterDeviceBean deviceBean : printerDeviceBeans) {
//遍歷打印機列表,找到對應的打印機,沒找到的就不打印 //遍歷打印機列表,找到對應的打印機,沒找到的就不打印
if (entry.getKey().equalsIgnoreCase(deviceBean.getName())) { if (entry.getKey().toLowerCase().equals(deviceBean.getName().toLowerCase())) {
if ((deviceBean.getPrinterName() != null && deviceBean.getPrinterName().toLowerCase().contains("EPSON".toLowerCase())) // if ((deviceBean.getPrinterName() != null && deviceBean.getPrinterName().toLowerCase().contains("EPSON".toLowerCase()))
&& (deviceBean.getModel() != null && deviceBean.getModel().toLowerCase().contains("TM-U220B".toLowerCase()))) { // && (deviceBean.getModel() != null && deviceBean.getModel().toLowerCase().contains("TM-U220B".toLowerCase()))) {
//針式打印機在上面處理 // //針式打印機在上面處理
} else { // } else {
Log.e("eee", entry.getKey() + "開始打印IP:" + deviceBean.getIp()); Log.e("eee", entry.getKey() + "開始打印IP:" + deviceBean.getIp());
printerInIt.ipDevicePrint(deviceBean, entry.getValue(), this, this); printerInIt.ipDevicePrint(deviceBean, entry.getValue(), this, this);
break; break;
} // }
} }
} }
} }
...@@ -390,7 +379,7 @@ public class PrjService extends Service implements PrintSocketHolder.OnStateChan ...@@ -390,7 +379,7 @@ public class PrjService extends Service implements PrintSocketHolder.OnStateChan
case PrintSocketHolder.ERROR_2: case PrintSocketHolder.ERROR_2:
Log.e("eee", "创建Socket失败"); Log.e("eee", "创建Socket失败");
//再次打開輪詢 //再次打開輪詢
updatePrjState(4); updatePrjState(1);
case PrintSocketHolder.ERROR_3: case PrintSocketHolder.ERROR_3:
Log.e("eee", "获取输出流失败"); Log.e("eee", "获取输出流失败");
break; break;
...@@ -403,6 +392,19 @@ public class PrjService extends Service implements PrintSocketHolder.OnStateChan ...@@ -403,6 +392,19 @@ public class PrjService extends Service implements PrintSocketHolder.OnStateChan
} }
} }
@Override
public void onPtrReceive(Printer printer, int i, PrinterStatusInfo printerStatusInfo, String s) {
//針式打印回調
if (i == 0) {
//打印成功
updatePrjState(3);
} else {
//打印失敗
updatePrjState(1);
}
startGetPrjInfo();
}
public class UpdateBean { public class UpdateBean {
private String id; private String id;
private int printerType; private int printerType;
......
package com.joe.print.mvp.print.usb;
import java.io.UnsupportedEncodingException;
import java.util.Vector;
public class EscCommand {
private Vector<Byte> command;
public EscCommand() {
this.command = new Vector<>(4096, 1024);
}
public void addArrayToCommand(byte[] array) {
for (byte anArray : array) {
this.command.add(anArray);
}
}
private void addStrToCommand(String str) {
byte[] bs = null;
if (!str.equals("")) {
try {
bs = str.getBytes("GB2312");
} catch (UnsupportedEncodingException var4) {
var4.printStackTrace();
}
if (bs != null) {
for (byte b : bs) {
this.command.add(b);
}
}
}
}
/**
* 添加文本
*
* @param text 文本
*/
public void addText(String text) {
this.addStrToCommand(text);
}
/**
* 添加空行
*
* @param n 行数
*/
public void addPrintAndFeedLines(byte n) {
byte[] command = new byte[]{27, 100, n};
this.addArrayToCommand(command);
}
/**
* 切纸命令
*/
public void addCutPaper() {
byte[] bytes = new byte[]{(byte) 29, (byte) 86, (byte) 0};
this.addArrayToCommand(bytes);
}
public void addCleanCache() {
byte[] bytes = {(byte) 27, (byte) 74, (byte) 0};
this.addArrayToCommand(bytes);
}
//0 居左 1居中 2居右
public void addSelectJustification(int just) {
byte[] command = new byte[]{27, 97, (byte) just};
this.addArrayToCommand(command);
}
/**
* 获取打印命令
*
* @return byte[] 打印命令
*/
public byte[] getByteArrayCommand() {
return convertToByteArray(getCommand());
}
public Vector<Byte> getCommand() {
return this.command;
}
private byte[] convertToByteArray(Vector<Byte> vector) {
if (vector == null || vector.isEmpty())
return new byte[0];
Byte[] bytes = vector.toArray(new Byte[vector.size()]);
return toPrimitive(bytes);
}
private byte[] toPrimitive(Byte[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return new byte[0];
} else {
byte[] result = new byte[array.length];
for (int i = 0; i < array.length; ++i) {
result[i] = array[i];
}
return result;
}
}
}
package com.joe.print.mvp.print.utils; package com.joe.print.mvp.print.usb;
import android.content.Context; import android.content.Context;
import android.hardware.usb.UsbDeviceConnection; import android.hardware.usb.UsbDeviceConnection;
......
package com.joe.print.mvp.print.utils; package com.joe.print.mvp.print.usb;
import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection; import android.hardware.usb.UsbDeviceConnection;
......
package com.joe.print.mvp.print.utils; package com.joe.print.mvp.print.usb;
import android.app.PendingIntent; import android.app.PendingIntent;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
......
...@@ -3,6 +3,7 @@ package com.joe.print.mvp.ui.activity; ...@@ -3,6 +3,7 @@ package com.joe.print.mvp.ui.activity;
import android.app.Dialog; import android.app.Dialog;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color; import android.graphics.Color;
import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.ColorDrawable;
import android.os.Bundle; import android.os.Bundle;
...@@ -17,15 +18,22 @@ import android.widget.TextView; ...@@ -17,15 +18,22 @@ import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.billy.cc.core.component.CC; import com.billy.cc.core.component.CC;
import com.billy.cc.core.component.CCResult; import com.billy.cc.core.component.CCResult;
import com.billy.cc.core.component.CCUtil; import com.billy.cc.core.component.CCUtil;
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication; import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.utils.other.SPUtils;
import com.gingersoft.gsa.cloud.base.utils.toast.ToastUtils; import com.gingersoft.gsa.cloud.base.utils.toast.ToastUtils;
import com.gingersoft.gsa.cloud.base.widget.DialogUtils;
import com.gingersoft.gsa.cloud.constans.PrintConstans; import com.gingersoft.gsa.cloud.constans.PrintConstans;
import com.gingersoft.gsa.cloud.database.bean.PrintCurrencyBean;
import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean; import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean;
import com.gingersoft.gsa.cloud.database.utils.PrinterDeviceDaoUtils; import com.gingersoft.gsa.cloud.database.utils.PrinterDeviceDaoUtils;
import com.gingersoft.gsa.cloud.print.PrintExecutor;
import com.gingersoft.gsa.cloud.print.PrintSocketHolder; import com.gingersoft.gsa.cloud.print.PrintSocketHolder;
import com.jess.arms.base.BaseActivity; import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent; import com.jess.arms.di.component.AppComponent;
...@@ -34,8 +42,21 @@ import com.joe.print.R; ...@@ -34,8 +42,21 @@ import com.joe.print.R;
import com.joe.print.di.component.DaggerPrintComponent; import com.joe.print.di.component.DaggerPrintComponent;
import com.joe.print.mvp.contract.PrintContract; import com.joe.print.mvp.contract.PrintContract;
import com.joe.print.mvp.presenter.PrintPresenter; import com.joe.print.mvp.presenter.PrintPresenter;
import com.joe.print.mvp.print.OpenCashBoxMaker;
import com.joe.print.mvp.print.PrintBill;
import com.joe.print.mvp.print.PrintCleanMachine;
import com.joe.print.mvp.print.PrintInstruction;
import com.joe.print.mvp.print.PrintListener; import com.joe.print.mvp.print.PrintListener;
import com.joe.print.mvp.print.PrintOtherOrder;
import com.joe.print.mvp.print.PrintOtherOrderClosing;
import com.joe.print.mvp.print.PrintPrjKitchen;
import com.joe.print.mvp.print.PrintServe;
import com.joe.print.mvp.print.PrintSlip;
import com.joe.print.mvp.print.PrintTest;
import com.joe.print.mvp.print.PrinterRoot; import com.joe.print.mvp.print.PrinterRoot;
import com.joe.print.mvp.print.utils.MyPrintUtils;
import com.joe.print.mvp.ui.adapter.DialogPrinterListAdapter;
import com.yanzhenjie.recyclerview.widget.DefaultItemDecoration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
...@@ -79,6 +100,9 @@ public class PrintActivity extends BaseActivity<PrintPresenter> implements Print ...@@ -79,6 +100,9 @@ public class PrintActivity extends BaseActivity<PrintPresenter> implements Print
private Dialog mLoadingDialog; private Dialog mLoadingDialog;
private TextView mTvLoadingTip; private TextView mTvLoadingTip;
private int type;
private boolean isShowDialog;
@Override @Override
public void setupActivityComponent(@NonNull AppComponent appComponent) { public void setupActivityComponent(@NonNull AppComponent appComponent) {
DaggerPrintComponent //如找不到该类,请编译一下项目 DaggerPrintComponent //如找不到该类,请编译一下项目
...@@ -110,36 +134,157 @@ public class PrintActivity extends BaseActivity<PrintPresenter> implements Print ...@@ -110,36 +134,157 @@ public class PrintActivity extends BaseActivity<PrintPresenter> implements Print
* 5:打印外賣接單 * 5:打印外賣接單
* 6:其他指令 * 6:其他指令
*/ */
int type = CCUtil.getNavigateParam(this, PRINT_TYPE, -1); type = CCUtil.getNavigateParam(this, PRINT_TYPE, -1);
boolean isShowDialog = CCUtil.getNavigateParam(this, PrintConstans.PRINT_LOADING, true); isShowDialog = CCUtil.getNavigateParam(this, PrintConstans.PRINT_LOADING, true);
if (isShowDialog) {
initDialog();
}
PrinterDeviceBean deviceBean = CCUtil.getNavigateParam(this, "deviceBean", null);
printerInIt = PrinterRoot.getPrinterByType(type); printerInIt = PrinterRoot.getPrinterByType(type);
if (printerInIt != null) { if (printerInIt != null) {
printerInIt.setmContext(mContext).setPrintListener(this); printerInIt.setmContext(mContext).setPrintListener(this);
} }
PrinterDeviceDaoUtils printerDeviceDaoUtils = new PrinterDeviceDaoUtils(this);
printerDeviceBeans = printerDeviceDaoUtils.queryAllPrinterDeviceBean(); // PrinterDeviceDaoUtils printerDeviceDaoUtils = new PrinterDeviceDaoUtils(this);
printerDeviceDaoUtils.closeConnection(); // printerDeviceBeans = printerDeviceDaoUtils.queryAllPrinterDeviceBean();
// printerDeviceDaoUtils.closeConnection();
// if (type == PrinterRoot.PRINT_TEST) {
// if (deviceBean != null) {
// printerInIt.ipDevicePrint(deviceBean, printerInIt.getPrintBitmap(mContext).get(""));
// } else {
// ToastUtils.show(mContext, "測試失敗");
// finish();
// }
// } else {
// if (printerDeviceBeans == null || printerDeviceBeans.size() <= 0) {
// mPresenter.getPrinterList(GsaCloudApplication.getRestaurantId(mContext));
// } else {
// printerInIt.print(printerDeviceBeans);
// }
// }
initPrintConfig();
}
private void initPrintConfig() {
PrintCurrencyBean printCurrencyBean = null;
PrinterDeviceBean defaultPrint;
//獲取通用打印配置,不同的打印
if (type == 0 || type == 1 || type == 2) {
//堂食的通用打印配置
printCurrencyBean = mPresenter.getPrintCurrencyBeanByType(this, 1);
} else if (type == 5 || type == 7) {
//外賣的通用打印配置
printCurrencyBean = mPresenter.getPrintCurrencyBeanByType(this, 2);
}
//獲取打印機列表
printerDeviceBeans = mPresenter.getAllPrintList(this);
if (type == PrinterRoot.PRINT_TEST) { if (type == PrinterRoot.PRINT_TEST) {
if (deviceBean != null) { //如果是打印測試
printerInIt.ipDevicePrint(deviceBean, printerInIt.getPrintBitmap(mContext).get("")); defaultPrint = CCUtil.getNavigateParam(this, "deviceBean", null);
} else {
// 獲取默認打印機,如果用戶沒有配置默認打印機,就取他最近使用的一個.
// 如果沒有最近使用的打印機,並且當前餐廳只有一台打印機,就用這一台打印機打印
defaultPrint = mPresenter.getDefaultPrintInList(printerDeviceBeans, (String) SPUtils.get(mContext, "defaultPrint", ""));
}
if (defaultPrint == null) {
//沒有默認打印機,查看當前餐廳有沒有打印機
//如果當前餐廳有打印機,彈出彈窗讓用戶選擇一個打印機打印
if (printerDeviceBeans != null && printerDeviceBeans.size() > 0) {
PrintCurrencyBean finalPrintCurrencyBean = printCurrencyBean;
new DialogUtils(mContext, R.layout.print_dialog_internet_list) {
@Override
public void initLayout(ViewHepler hepler, Dialog dialog) {
RecyclerView mRvPrintList = hepler.getView(R.id.rv_print_list);
DialogPrinterListAdapter printListAdapter = new DialogPrinterListAdapter(printerDeviceBeans, mContext);
mRvPrintList.setLayoutManager(new LinearLayoutManager(mContext));
//分割线
mRvPrintList.addItemDecoration(new DefaultItemDecoration(ContextCompat.getColor(mContext, R.color.line_color)));
mRvPrintList.setAdapter(printListAdapter);
printListAdapter.setOnItemClickListener((adapter, view, position) -> {
//用戶選擇的ip打印機打印
PrinterDeviceBean defaultPrint = configPrinterProperties(finalPrintCurrencyBean, printerDeviceBeans.get(position));
printByDevice(defaultPrint);
SPUtils.put(mContext, "defaultPrint", printerDeviceBeans.get(position).getName());
dialog.dismiss();
});
}
}
.setHeight(ArmsUtils.getScreenHeidth(mContext) / 2)
.setWidth((int) (ArmsUtils.getScreenWidth(mContext) * 0.8))
.show();
} else { } else {
ToastUtils.show(mContext, "測試失敗"); //沒有打印機
finish(); ToastUtils.show(mContext, "沒有打印機,請先添加打印機");
} }
} else { } else {
if (printerDeviceBeans == null || printerDeviceBeans.size() <= 0) { defaultPrint = configPrinterProperties(printCurrencyBean, defaultPrint);
mPresenter.getPrinterList(GsaCloudApplication.getRestaurantId(mContext)); printByDevice(defaultPrint);
}
}
//打印邏輯,獲取對應的打印配置--打印機或是通用配置
//根據配置生成配置好的圖片----生成圖片邏輯:把打印的單分為幾個模塊,再由不同的單拼接出對應的單,(如果是針式,生成對應的文字)
//再獲取打印方式(IP、本機、USB、藍牙或其他的),調用打印
private void printByDevice(PrinterDeviceBean defaultPrint) {
if (isShowDialog) {
initDialog();
}
//獲取對應的打印類
printerInIt = mPresenter.getPrinterByType(type);
if (printerInIt instanceof PrintInstruction) {
//開錢箱
PrintExecutor executor = new PrintExecutor(defaultPrint);
executor.doPrinterRequestAsync(new OpenCashBoxMaker());
} else {
List<Bitmap> bitmaps = printerInIt.getPrintBitmap(mContext, defaultPrint).get("");
if (bitmaps != null && bitmaps.size() > 0) {
if (defaultPrint.getPrinterDeviceType() == 1) {
//IP打印
printerInIt.ipDevicePrint(defaultPrint, bitmaps);
} else if (defaultPrint.getPrinterDeviceType() == 2) {
//本地N5或Sunmi打印
printerInIt.locationPrint(bitmaps, this);
} else if (defaultPrint.getPrinterDeviceType() == 3) {
//USB打印打印
printerInIt.usbPrint(mContext, bitmaps);
} else {
ToastUtils.show(mContext, "未找到對應的打印類型");
finish();
}
} else { } else {
printerInIt.print(printerDeviceBeans); //打印失敗
Log.e("eee", "打印失敗,沒有生成對應的圖片");
finish();
}
}
}
/**
* 配置打印機屬性,因為有部分屬性是預設的,如果是預設的,就取通用打印配置
*/
private PrinterDeviceBean configPrinterProperties(PrintCurrencyBean printCurrencyBean, PrinterDeviceBean defaultPrint) {
if (printCurrencyBean != null && defaultPrint != null) {
if (defaultPrint.getFoodIsBold() == 0) {
defaultPrint.setFoodIsBold(printCurrencyBean.getFoodIsBold());
}
if (defaultPrint.getFoodFont().equals("0")) {
defaultPrint.setFoodFont(printCurrencyBean.getFoodFont());
}
if (defaultPrint.getFoodIsItalic() == 0) {
defaultPrint.setFoodIsItalic(printCurrencyBean.getFoodIsItalic());
}
if (defaultPrint.getModifierIsBold() == 0) {
defaultPrint.setModifierIsBold(printCurrencyBean.getModifierIsBold());
}
if (defaultPrint.getModifierFont().equals("0")) {
defaultPrint.setModifierFont(printCurrencyBean.getModifierFont());
}
if (defaultPrint.getModifierIsItalic() == 0) {
defaultPrint.setModifierIsItalic(printCurrencyBean.getModifierIsItalic());
}
if (defaultPrint.getNumberIsFlip() == 0) {
defaultPrint.setNumberIsFlip(printCurrencyBean.getNumberIsFlip());
} }
} }
return defaultPrint;
} }
private void initDialog() { private void initDialog() {
...@@ -152,7 +297,6 @@ public class PrintActivity extends BaseActivity<PrintPresenter> implements Print ...@@ -152,7 +297,6 @@ public class PrintActivity extends BaseActivity<PrintPresenter> implements Print
Window window = mLoadingDialog.getWindow(); Window window = mLoadingDialog.getWindow();
window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
// window.getDecorView().setBackgroundResource(android.R.color.transparent); // window.getDecorView().setBackgroundResource(android.R.color.transparent);
mLoadingDialog.setContentView(view, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)); mLoadingDialog.setContentView(view, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
if (!this.isFinishing()) { if (!this.isFinishing()) {
mLoadingDialog.show(); mLoadingDialog.show();
...@@ -314,8 +458,8 @@ public class PrintActivity extends BaseActivity<PrintPresenter> implements Print ...@@ -314,8 +458,8 @@ public class PrintActivity extends BaseActivity<PrintPresenter> implements Print
@Override @Override
public void showPrinterList(List<PrinterDeviceBean> deviceBeans) { public void showPrinterList(List<PrinterDeviceBean> deviceBeans) {
printerDeviceBeans = deviceBeans; // printerDeviceBeans = deviceBeans;
printerInIt.print(printerDeviceBeans); // printerInIt.print(printerDeviceBeans);
} }
private void addPrintDevice() { private void addPrintDevice() {
...@@ -327,20 +471,20 @@ public class PrintActivity extends BaseActivity<PrintPresenter> implements Print ...@@ -327,20 +471,20 @@ public class PrintActivity extends BaseActivity<PrintPresenter> implements Print
@Override @Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ADD_PRINT_CODE && resultCode == PrintActivity.ADD_PRINT_CODE) { // if (requestCode == ADD_PRINT_CODE && resultCode == PrintActivity.ADD_PRINT_CODE) {
//添加打印機成功, // //添加打印機成功,
if (data != null && data.getSerializableExtra("printDevice") != null) { // if (data != null && data.getSerializableExtra("printDevice") != null) {
List<PrinterDeviceBean> printerDeviceBeans = new ArrayList<>(); // List<PrinterDeviceBean> printerDeviceBeans = new ArrayList<>();
printerDeviceBeans.add((PrinterDeviceBean) data.getSerializableExtra("printDevice")); // printerDeviceBeans.add((PrinterDeviceBean) data.getSerializableExtra("printDevice"));
printerInIt.print(printerDeviceBeans); // printerInIt.print(printerDeviceBeans);
} else { // } else {
ToastUtils.show(mContext, "未獲取到打印機"); // ToastUtils.show(mContext, "未獲取到打印機");
printFile(); // printFile();
} // }
} else { // } else {
ToastUtils.show(mContext, "未獲取到打印機"); // ToastUtils.show(mContext, "未獲取到打印機");
printFile(); // printFile();
} // }
} }
@Override @Override
......
package com.joe.print.mvp.ui.activity; package com.joe.print.mvp.ui.activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle; import android.os.Bundle;
import android.util.Log; import android.util.Log;
import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatActivity;
import com.gingersoft.gsa.cloud.base.utils.toast.ToastUtils;
import com.gingersoft.gsa.cloud.base.utils.view.ImageUtils;
import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean; import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean;
import com.gingersoft.gsa.cloud.print.PrintExecutor; import com.gingersoft.gsa.cloud.print.PrintExecutor;
import com.gingersoft.gsa.cloud.print.PrintSocketHolder; import com.gingersoft.gsa.cloud.print.PrintSocketHolder;
import com.gingersoft.gsa.cloud.print.PrinterWriter;
import com.gingersoft.gsa.cloud.print.PrinterWriter80mm; import com.gingersoft.gsa.cloud.print.PrinterWriter80mm;
import com.gingersoft.gsa.cloud.print.PrinterWriterExecutor;
import com.joe.print.R; import com.joe.print.R;
import com.joe.print.mvp.model.bean.PrintInfoBean; import com.joe.print.mvp.model.bean.PrintInfoBean;
import com.joe.print.mvp.print.PrintTest;
import com.joe.print.mvp.print.TestPrintMaker; import com.joe.print.mvp.print.TestPrintMaker;
import com.joe.print.mvp.print.common.PrinterFinderCallback; import com.joe.print.mvp.print.common.PrinterFinderCallback;
import com.joe.print.mvp.print.common.SendCallback; import com.joe.print.mvp.print.common.SendCallback;
import com.joe.print.mvp.print.common.SendResultCode; import com.joe.print.mvp.print.common.SendResultCode;
import com.joe.print.mvp.print.utils.UsbPrinter; import com.joe.print.mvp.print.usb.EscCommand;
import com.joe.print.mvp.print.usb.UsbPrint;
import com.joe.print.mvp.print.usb.UsbPrinter;
import com.joe.print.mvp.print.usb.UsbPrinterFinder;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects;
import static com.gingersoft.gsa.cloud.print.PrinterUtils.binaryStrToHexString;
import static com.gingersoft.gsa.cloud.print.PrinterUtils.hexListToByte;
import static com.gingersoft.gsa.cloud.print.PrinterUtils.hexStringToBytes;
import static com.joe.print.mvp.print.SendPrint.draw2PxPoint2;
import static com.joe.print.mvp.print.utils.BytesUtil.getBytesFromBitMap;
public class PrintTestActivity extends AppCompatActivity implements PrintSocketHolder.OnStateChangedListener, PrintExecutor.OnPrintResultListener { public class PrintTestActivity extends AppCompatActivity implements PrintSocketHolder.OnStateChangedListener, PrintExecutor.OnPrintResultListener {
private int lineLength = 24;//一行42個 private int lineLength = 24;//一行42個
private int LEFT_TEXT_LENGTH = 8; private int LEFT_TEXT_LENGTH = 8;
private String json = "{\n" +
" \"success\":true,\n" +
" \"sysTime\":1595414257771,\n" +
" \"data\":[\n" +
" {\n" +
" \"MEMBER_NAME\":\"\",\n" +
" \"delivery_man_phone_num\":\"\",\n" +
" \"payTime\":\"2020-07-21 12:04:26.0\",\n" +
" \"discount_amount\":0,\n" +
" \"PHONE\":\"13825748837\",\n" +
" \"memberTypeId\":32,\n" +
" \"orderPayType\":1,\n" +
" \"orderStatus\":2,\n" +
" \"ORDER_NO\":\"26200123048322822\",\n" +
" \"remark\":\"\",\n" +
" \"pid\":0,\n" +
" \"addressDetail\":\"香港長沙灣長沙灣道长沙湾政府合署你\",\n" +
" \"payType\":5,\n" +
" \"DELIVERY_CHARGE\":10,\n" +
" \"SEND_TIME\":\"盡快送達 預計 13:04-13:29\",\n" +
" \"sendMobile\":\"\",\n" +
" \"ID\":11116180,\n" +
" \"CREATE_TIME\":\"2020-07-21 12:04:26.0\",\n" +
" \"takeFoodCode\":\"0633\",\n" +
" \"billNo\":\"\",\n" +
" \"RECEIVER\":\"xu 先生\",\n" +
" \"Order_ID\":11116180,\n" +
" \"NUMBER\":1,\n" +
" \"PRICE\":29.29,\n" +
" \"delivery_man_name\":\"\",\n" +
" \"Lunchbox\":3,\n" +
" \"PRODUCT_NAME\":[\n" +
" {\n" +
" \"odsId\":\"48864514\",\n" +
" \"PRICE\":\"29.3\",\n" +
" \"num\":\"1\",\n" +
" \"pid\":\"0\",\n" +
" \"PRODUCT_NAME\":\"精選牛肉asdfh sdfjabs sdf sdfsafasf\",\n" +
" \"child\":[\n" +
" {\n" +
" \"odsId\":\"48864515\",\n" +
" \"PRICE\":\"0.0\",\n" +
" \"num\":\"1\",\n" +
" \"pid\":\"48864514\",\n" +
" \"PRODUCT_NAME\":\"甜品asdf sdafadf sadfaf\",\n" +
" \"child\":[\n" +
" {\n" +
" \"odsId\":\"48864516\",\n" +
" \"PRICE\":\"10.0\",\n" +
" \"num\":\"1\",\n" +
" \"pid\":\"48864515\",\n" +
" \"PRODUCT_NAME\":\"默認細項1asfdsdfa\"\n" +
" },\n" +
" {\n" +
" \"odsId\":\"48864517\",\n" +
" \"PRICE\":\"10.0\",\n" +
" \"num\":\"1\",\n" +
" \"pid\":\"48864515\",\n" +
" \"PRODUCT_NAME\":\"默認細項2asfasf asdfa\"\n" +
" },\n" +
" {\n" +
" \"odsId\":\"48864518\",\n" +
" \"PRICE\":\"1.0\",\n" +
" \"num\":\"1\",\n" +
" \"pid\":\"48864515\",\n" +
" \"PRODUCT_NAME\":\"細項默認1\"\n" +
" },\n" +
" {\n" +
" \"odsId\":\"48864519\",\n" +
" \"PRICE\":\"1.0\",\n" +
" \"num\":\"1\",\n" +
" \"pid\":\"48864515\",\n" +
" \"PRODUCT_NAME\":\"細項默認3\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"odsId\":\"48864520\",\n" +
" \"PRICE\":\"0.0\",\n" +
" \"num\":\"1\",\n" +
" \"pid\":\"48864514\",\n" +
" \"PRODUCT_NAME\":\"雞飯(四客)\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" ],\n" +
" \"odsId\":48864514,\n" +
" \"order_from\":7,\n" +
" \"sender\":\"\",\n" +
" \"PAY_AMOUNT\":64.3,\n" +
" \"levelName1\":\"GS基本用戶\",\n" +
" \"TOTAL_AMOUNT\":\"64.3\",\n" +
" \"status\":2\n" +
" }\n" +
" ]\n" +
"}";
private UsbPrint usbPrint;
private List<UsbPrinter> usbPrinters;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setContentView(R.layout.activity_print_test); setContentView(R.layout.activity_print_test);
PrinterDeviceBean printerDeviceBean = new PrinterDeviceBean("192.168.1.218", 9100, "400"); }
List<PrintInfoBean> printInfoBeans = new ArrayList<>();
// printInfoBeans.add(new PrintInfoBean(new String[]{"測試一行多少個字測試一行多少個字測試一"}, new double[]{2}, new String[]{"tw"})); /**
// printInfoBeans.add(new PrintInfoBean(new String[]{"asdfskjflsjflsjlfjslfjsldjflsjfsd"}, new double[]{2}, new String[]{"tw"})); * 解码图片
// printInfoBeans.add(new PrintInfoBean(new String[]{"測試一行多少個字測試一行多少個字測試一"}, new double[]{1}, new String[]{"tw"})); *
// printInfoBeans.add(new PrintInfoBean(new String[]{"asdfskjflsjflsjlfjslfjsldjflsjfsd"}, new double[]{1}, new String[]{"tw"})); * @param image 图片
// printInfoBeans.add(new PrintInfoBean(new String[]{"純屬餐廳"}, new double[]{1}, new String[]{"tw"})); * @param parting 高度分割值
* @return 数据流
printInfoBeans.add(new PrintInfoBean(new String[]{"外賣"}, new Boolean[]{true}, new Double[]{2d}, 0)); */
printInfoBeans.add(new PrintInfoBean(new String[]{"訂單碼:", "0046"}, new Boolean[]{false, true}, new Double[]{1d, 2d}, 0)); public static byte[] decodeBitmapToDataList(Bitmap image, int parting) {
printInfoBeans.add(new PrintInfoBean(new String[]{"落單時間:", "07-13 19:05"}, new Double[]{1d}, 0)); if (parting <= 0 || parting > 255)
printInfoBeans.add(new PrintInfoBean(new String[]{"D1廚房", "BARRY1"}, new Double[]{1d}, 0)); parting = 255;
printInfoBeans.add(new PrintInfoBean(new String[]{getLineBorder("", 1)}, 0)); if (image == null)
printInfoBeans.add(new PrintInfoBean(new String[]{"1", "食品名稱"}, new Boolean[]{true}, new Double[]{2d}, 0)); return null;
printInfoBeans.add(new PrintInfoBean(new String[]{"1", " 細項名稱"}, new Boolean[]{true}, new Double[]{2d}, 0)); final int width = image.getWidth();
final int height = image.getHeight();
printInfoBeans.add(new PrintInfoBean(new String[]{"精選牛肉 ", "x1 ", " 29.3"}, new Boolean[]{true}, new Double[]{1d}, 0)); if (width <= 0 || height <= 0)
printInfoBeans.add(new PrintInfoBean(new String[]{"牛肉名字"}, new Boolean[]{true}, new Double[]{1d}, 0)); return null;
if (width > 2040) {
findViewById(R.id.btn_test).setOnClickListener(view -> { // 8位9针,宽度限制2040像素(但一般纸张都没法打印那么宽,但并不影响打印)
//打印測試 final float scale = 2040 / (float) width;
PrintExecutor executor = new PrintExecutor(printerDeviceBean); Matrix matrix = new Matrix();
executor.setOnStateChangedListener(this); matrix.postScale(scale, scale);
executor.setOnPrintResultListener(this); Bitmap resizeImage;
TestPrintMaker maker = null;
try { try {
maker = new TestPrintMaker(new PrinterWriter80mm(255), printInfoBeans); resizeImage = Bitmap.createBitmap(image, 0, 0, width, height, matrix, true);
} catch (IOException e) { } catch (OutOfMemoryError e) {
e.printStackTrace(); return null;
} }
executor.doPrinterRequestAsync(maker); resizeImage.recycle();
}); return decodeBitmapToDataList(resizeImage, parting);
}
// 宽命令
String widthHexString = Integer.toHexString(width % 8 == 0 ? width / 8 : (width / 8 + 1));
if (widthHexString.length() > 2) {
// 超过2040像素才会到达这里
return null;
} else if (widthHexString.length() == 1) {
widthHexString = "0" + widthHexString;
}
widthHexString += "00";
// 每行字节数(除以8,不足补0)
String zeroStr = "";
int zeroCount = width % 8;
if (zeroCount > 0) {
for (int i = 0; i < (8 - zeroCount); i++) {
//noinspection StringConcatenationInLoop
zeroStr += "0";
}
}
ArrayList<String> commandList = new ArrayList<>();
// 高度每parting像素进行一次分割
int time = height % parting == 0 ? height / parting : (height / parting + 1);// 循环打印次数
for (int t = 0; t < time; t++) {
int partHeight = t == time - 1 ? height % parting : parting;// 分段高度
// 高命令
String heightHexString = Integer.toHexString(partHeight);
if (heightHexString.length() > 2) {
// 超过255像素才会到达这里
return null;
} else if (heightHexString.length() == 1) {
heightHexString = "0" + heightHexString;
}
heightHexString += "00";
// 宽高指令
String commandHexString = "1D763000";
commandList.add(commandHexString + widthHexString + heightHexString);
ArrayList<String> list = new ArrayList<>(); //binaryString list
StringBuilder sb = new StringBuilder();
// 像素二值化,非黑即白
for (int i = 0; i < partHeight; i++) {
sb.delete(0, sb.length());
for (int j = 0; j < width; j++) {
// 实际在图片中的高度
int startHeight = t * parting + i;
//得到当前像素的值
int color = image.getPixel(j, startHeight);
int red, green, blue;
if (image.hasAlpha()) {
//得到alpha通道的值
int alpha = Color.alpha(color);
//得到图像的像素RGB的值
red = Color.red(color);
green = Color.green(color);
blue = Color.blue(color);
final float offset = alpha / 255.0f;
// 根据透明度将白色与原色叠加
red = 0xFF + (int) Math.ceil((red - 0xFF) * offset);
green = 0xFF + (int) Math.ceil((green - 0xFF) * offset);
blue = 0xFF + (int) Math.ceil((blue - 0xFF) * offset);
} else {
//得到图像的像素RGB的值
red = Color.red(color);
green = Color.green(color);
blue = Color.blue(color);
}
// 接近白色改为白色。其余黑色
if (red > 160 && green > 160 && blue > 160)
sb.append("0");
else
sb.append("1");
}
// 每一行结束时,补充剩余的0
if (zeroCount > 0) {
sb.append(zeroStr);
}
list.add(sb.toString());
}
// binaryStr每8位调用一次转换方法,再拼合
ArrayList<String> bmpHexList = new ArrayList<>();
for (String binaryStr : list) {
sb.delete(0, sb.length());
for (int i = 0; i < binaryStr.length(); i += 8) {
String str = binaryStr.substring(i, i + 8);
// 2进制转成16进制
String hexString = binaryStrToHexString(str);
sb.append(hexString);
}
bmpHexList.add(sb.toString());
}
// 数据指令
commandList.addAll(bmpHexList);
}
// byte[] data = null;
// for (String hexStr : commandList) {
// data.add(hexStringToBytes(hexStr));
// }
return hexListToByte(commandList);
} }
private void printTestText(UsbPrinter printer) { private void printTestText(UsbPrinter printer) {
...@@ -76,8 +293,8 @@ public class PrintTestActivity extends AppCompatActivity implements PrintSocketH ...@@ -76,8 +293,8 @@ public class PrintTestActivity extends AppCompatActivity implements PrintSocketH
// esc.addPrintAndFeedLines((byte) 8); // esc.addPrintAndFeedLines((byte) 8);
// esc.addArrayToCommand(draw2PxPoint2(BitmapFactory.decodeResource(getResources(), R.mipmap.meal_takeaway_mode))); // esc.addArrayToCommand(draw2PxPoint2(BitmapFactory.decodeResource(getResources(), R.mipmap.meal_takeaway_mode)));
// esc.addCutPaper(); // esc.addCutPaper();
//esc.addCleanCache(); // esc.addCleanCache();
// usbPrint.sendPrintCommand(printer, esc.getByteArrayCommand()); // usbPrint.sendPrintCommand(printer, );
} }
@Override @Override
...@@ -137,12 +354,15 @@ public class PrintTestActivity extends AppCompatActivity implements PrintSocketH ...@@ -137,12 +354,15 @@ public class PrintTestActivity extends AppCompatActivity implements PrintSocketH
@Override @Override
public void onFound(UsbPrinter usbPrinter) { public void onFound(UsbPrinter usbPrinter) {
//listAdapter.addData(usbPrinter); //listAdapter.addData(usbPrinter);
ToastUtils.show(PrintTestActivity.this, "onFound deviceName = " + usbPrinter.getPrinterName());
Log.d(TAG, "onFound deviceName = " + usbPrinter.getPrinterName()); Log.d(TAG, "onFound deviceName = " + usbPrinter.getPrinterName());
} }
@Override @Override
public void onFinished(List<UsbPrinter> usbPrinters) { public void onFinished(List<UsbPrinter> printers) {
Log.d(TAG, "printCount = " + usbPrinters.size()); ToastUtils.show(PrintTestActivity.this, "printCount = " + printers.size());
usbPrinters = printers;
Log.d(TAG, "printCount = " + printers.size());
// listAdapter.replaceDatas(usbPrinters); // listAdapter.replaceDatas(usbPrinters);
} }
}; };
......
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical">
<LinearLayout
android:id="@+id/layout_dining_table"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_print_model_dining_table"
style="@style/Print_text_style"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
tools:text="餐檯:1111" />
<TextView
android:id="@+id/tv_print_model_people"
style="@style/Print_text_style"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
tools:text="人數:10"/>
</LinearLayout>
<TextView
android:id="@+id/tv_print_model_order_number"
style="@style/Print_text_style"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="單號:42345" />
<TextView
android:id="@+id/tv_print_model_data"
style="@style/Print_text_style"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="下單時間:2020-05-06 12:11:23" />
</LinearLayout>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="@+id/tv_thank_you_text"
style="@style/Print_text_style"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
tools:text="Thank you!" />
<TextView
android:id="@+id/tv_checkout_time"
style="@style/Print_text_style"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="2020-01-09 上午 11:16:15" />
</LinearLayout>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
style="@style/Print_text_style"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:maxLines="1" />
<TextView
style="@style/Print_text_style"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:maxLines="1"
android:text="@string/print_split_line" />
</LinearLayout>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical">
<TextView
android:id="@+id/print_brand_name"
style="@style/Print_text_style"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:gravity="center"
tools:text="品牌名" />
<TextView
android:id="@+id/print_restaurant_name"
style="@style/Print_text_style"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center"
tools:text="餐廳名" />
</LinearLayout>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment