Драйверы торгового оборудования v.9
FptrExampleActivity.java
1 package com.atol.drivers.examples.fptrexample;
2 
3 import android.app.Activity;
4 import android.content.Context;
5 import android.content.Intent;
6 import android.content.SharedPreferences;
7 import android.os.AsyncTask;
8 import android.os.Bundle;
9 import android.view.View;
10 import android.widget.Button;
11 import android.widget.LinearLayout;
12 import android.widget.TextView;
13 
14 import com.atol.drivers.fptr.Fptr;
15 import com.atol.drivers.fptr.IFptr;
16 import com.atol.drivers.fptr.settings.SettingsActivity;
17 
18 import java.math.BigDecimal;
19 import java.util.Random;
20 
21 public class FptrExampleActivity extends Activity {
22  private static final String FPTR_PREFERENCES = "FPTR_PREFERENCES";
23  private static final int REQUEST_SHOW_SETTINGS = 1;
24  private Button runButton;
25  private Button settingsButton;
26  private Button testButton;
27  private TextView log;
28  private SharedPreferences preferences;
29  private Button cancelButton;
30  private LinearLayout buttonsLayout;
31  private static final boolean PRINT_FISCAL_CHECK = true;
32  private static final boolean PRINT_NONFISCAL_CHECK = true;
33  private static final boolean USE_FZ54 = true;
34 
35  @Override
36  protected void onCreate(Bundle savedInstanceState) {
37  super.onCreate(savedInstanceState);
38 
39  preferences = getSharedPreferences(FPTR_PREFERENCES, Context.MODE_PRIVATE);
40 
41  setContentView(R.layout.activity_main);
42  buttonsLayout = (LinearLayout) findViewById(R.id.buttons_layout);
43  settingsButton = (Button) findViewById(R.id.settings_button);
44  testButton = (Button) findViewById(R.id.test_button);
45  runButton = (Button) findViewById(R.id.run_button);
46  cancelButton = (Button) findViewById(R.id.cancel_button);
47  log = (TextView) findViewById(R.id.log);
48 
49  settingsButton.setOnClickListener(new View.OnClickListener() {
50  @Override
51  public void onClick(View v) {
52  Intent intent = new Intent(FptrExampleActivity.this, SettingsActivity.class);
53  String settings = getSettings();
54  if (settings == null) {
55  settings = getDefaultSettings();
56  }
57  intent.putExtra(SettingsActivity.DEVICE_SETTINGS, settings);
58  startActivityForResult(intent, REQUEST_SHOW_SETTINGS);
59  }
60  });
61 
62  testButton.setOnClickListener(new View.OnClickListener() {
63  AsyncTask<Void, String, Void> task;
64 
65  @Override
66  public void onClick(View v) {
67  log.setText("");
68  task = new AsyncTask<Void, String, Void>() {
69  private IFptr fptr;
70 
71  private void checkError() throws DriverException {
72  int rc = fptr.get_ResultCode();
73  if (rc < 0) {
74  String rd = fptr.get_ResultDescription(), bpd = null;
75  if (rc == -6) {
76  bpd = fptr.get_BadParamDescription();
77  }
78  if (bpd != null) {
79  throw new DriverException(String.format("[%d] %s (%s)", rc, rd, bpd));
80  } else {
81  throw new DriverException(String.format("[%d] %s", rc, rd));
82  }
83  }
84  }
85 
86  @Override
87  protected void onPreExecute() {
88  buttonsLayout.setVisibility(View.GONE);
89  }
90 
91  @Override
92  protected void onPostExecute(Void result) {
93  buttonsLayout.setVisibility(View.VISIBLE);
94  }
95 
96  @Override
97  protected Void doInBackground(Void... params) {
98  fptr = new Fptr();
99  try {
100  fptr.create(getApplication());
101  publishProgress("Загрузка настроек");
102  if (fptr.put_DeviceSettings(getSettings()) < 0) {
103  checkError();
104  }
105  publishProgress("Установка соединения...");
106  if (fptr.put_DeviceEnabled(true) < 0) {
107  checkError();
108  }
109  publishProgress("OK");
110  publishProgress("Проверка связи...");
111  if (fptr.GetStatus() < 0) {
112  checkError();
113  }
114  publishProgress("OK");
115  } catch (Exception e) {
116  publishProgress(e.toString());
117  } finally {
118  fptr.destroy();
119  }
120  return null;
121  }
122 
123  @Override
124  protected void onProgressUpdate(String... values) {
125  if (values == null || values.length == 0) {
126  return;
127  }
128  logAdd(values[0]);
129  }
130 
131  };
132  task.execute();
133  }
134  });
135 
136  runButton.setOnClickListener(new View.OnClickListener() {
137  AsyncTask<Void, String, Void> task;
138 
139  @Override
140  public void onClick(View v) {
141  log.setText("");
142  task = new AsyncTask<Void, String, Void>() {
143  private IFptr fptr;
144 
145  private void checkError() throws DriverException {
146  int rc = fptr.get_ResultCode();
147  if (rc < 0) {
148  String rd = fptr.get_ResultDescription(), bpd = null;
149  if (rc == -6) {
150  bpd = fptr.get_BadParamDescription();
151  }
152  if (bpd != null) {
153  throw new DriverException(String.format("[%d] %s (%s)", rc, rd, bpd));
154  } else {
155  throw new DriverException(String.format("[%d] %s", rc, rd));
156  }
157  }
158  }
159 
160  private void printText(String text, int alignment, int wrap) throws DriverException {
161  if (fptr.put_Caption(text) < 0) {
162  checkError();
163  }
164  if (fptr.put_TextWrap(wrap) < 0) {
165  checkError();
166  }
167  if (fptr.put_Alignment(alignment) < 0) {
168  checkError();
169  }
170  if (fptr.PrintString() < 0) {
171  checkError();
172  }
173  }
174 
175  private void printText(String text) throws DriverException {
176  printText(text, IFptr.ALIGNMENT_CENTER, IFptr.WRAP_LINE);
177  }
178 
179  private void openCheck(int type) throws DriverException {
180  if (fptr.put_Mode(IFptr.MODE_REGISTRATION) < 0) {
181  checkError();
182  }
183  if (fptr.SetMode() < 0) {
184  checkError();
185  }
186  if (fptr.put_CheckType(type) < 0) {
187  checkError();
188  }
189  if (fptr.OpenCheck() < 0) {
190  checkError();
191  }
192  }
193 
194  private void closeCheck(int typeClose) throws DriverException {
195  if (fptr.put_TypeClose(typeClose) < 0) {
196  checkError();
197  }
198  if (fptr.CloseCheck() < 0) {
199  checkError();
200  }
201  }
202 
203  private void registration(String name, double price, double quantity) throws DriverException {
204  if (fptr.put_Quantity(quantity) < 0) {
205  checkError();
206  }
207  if (fptr.put_Price(price) < 0) {
208  checkError();
209  }
210  if (fptr.put_TextWrap(IFptr.WRAP_WORD) < 0) {
211  checkError();
212  }
213  if (fptr.put_Name(name) < 0) {
214  checkError();
215  }
216  if (fptr.Registration() < 0) {
217  checkError();
218  }
219  }
220 
221  private void registrationFZ54(String name, double price, double quantity,
222  double positionSum, int taxNumber) throws DriverException {
223  if (fptr.put_TaxNumber(taxNumber) < 0) {
224  checkError();
225  }
226  if (fptr.put_PositionSum(positionSum) < 0) {
227  checkError();
228  }
229  if (fptr.put_Quantity(quantity) < 0) {
230  checkError();
231  }
232  if (fptr.put_Price(price) < 0) {
233  checkError();
234  }
235  if (fptr.put_TextWrap(IFptr.WRAP_WORD) < 0) {
236  checkError();
237  }
238  if (fptr.put_Name(name) < 0) {
239  checkError();
240  }
241  if (fptr.Registration() < 0) {
242  checkError();
243  }
244  }
245 
246  private void payment(double sum, int type) throws DriverException {
247  if (fptr.put_Summ(sum) < 0) {
248  checkError();
249  }
250  if (fptr.put_TypeClose(type) < 0) {
251  checkError();
252  }
253  if (fptr.Payment() < 0) {
254  checkError();
255  }
256  publishProgress(String.format("Remainder: %.2f, Change: %.2f", fptr.get_Remainder(), fptr.get_Change()));
257  }
258 
259  private void reportZ() throws DriverException {
260  if (fptr.put_Mode(IFptr.MODE_REPORT_CLEAR) < 0) {
261  checkError();
262  }
263  if (fptr.SetMode() < 0) {
264  checkError();
265  }
266  if (fptr.put_ReportType(IFptr.REPORT_Z) < 0) {
267  checkError();
268  }
269  if (fptr.Report() < 0) {
270  checkError();
271  }
272  }
273 
274  private void printFooter() throws DriverException {
275  if (fptr.put_Mode(IFptr.MODE_REPORT_NO_CLEAR) < 0) {
276  checkError();
277  }
278  if (fptr.SetMode() < 0) {
279  checkError();
280  }
281  if (fptr.PrintFooter() < 0) {
282  checkError();
283  }
284  }
285 
286  private void printBarcode(int type, String barcode, double scale) throws DriverException {
287  if (fptr.put_Alignment(IFptr.ALIGNMENT_CENTER) < 0) {
288  checkError();
289  }
290  if (fptr.put_BarcodeType(type) < 0) {
291  checkError();
292  }
293  if (fptr.put_Barcode(barcode) < 0) {
294  checkError();
295  }
296  if (type == IFptr.BARCODE_TYPE_QRCODE) {
297  if (fptr.put_Height(0) < 0) {
298  checkError();
299  }
300  } else {
301  if (fptr.put_Height(50) < 0) {
302  checkError();
303  }
304  }
305  if (fptr.put_BarcodePrintType(IFptr.BARCODE_PRINTTYPE_AUTO) < 0) {
306  checkError();
307  }
308  if (fptr.put_PrintBarcodeText(false) < 0) {
309  checkError();
310  }
311  if (fptr.put_BarcodeControlCode(true) < 0) {
312  checkError();
313  }
314  if (fptr.put_Scale(scale) < 0) {
315  checkError();
316  }
317  if (fptr.put_BarcodeCorrection(0) < 0) {
318  checkError();
319  }
320  if (fptr.put_BarcodeColumns(3) < 0) {
321  checkError();
322  }
323  if (fptr.put_BarcodeRows(1) < 0) {
324  checkError();
325  }
326  if (fptr.put_BarcodeProportions(50) < 0) {
327  checkError();
328  }
329  if (fptr.put_BarcodeUseProportions(true) < 0) {
330  checkError();
331  }
332  if (fptr.put_BarcodePackingMode(IFptr.BARCODE_PDF417_PACKING_MODE_DEFAULT) < 0) {
333  checkError();
334  }
335  if (fptr.put_BarcodePixelProportions(300) < 0) {
336  checkError();
337  }
338  if (fptr.PrintBarcode() < 0) {
339  checkError();
340  }
341  }
342 
343  private void discount(double sum, int type, int destination) throws DriverException {
344  if (fptr.put_Summ(sum) < 0) {
345  checkError();
346  }
347  if (fptr.put_DiscountType(type) < 0) {
348  checkError();
349  }
350  if (fptr.put_Destination(destination) < 0) {
351  checkError();
352  }
353  if (fptr.Discount() < 0) {
354  checkError();
355  }
356  }
357 
358  private void charge(double sum, int type, int destination) throws DriverException {
359  if (fptr.put_Summ(sum) < 0) {
360  checkError();
361  }
362  if (fptr.put_DiscountType(type) < 0) {
363  checkError();
364  }
365  if (fptr.put_Destination(destination) < 0) {
366  checkError();
367  }
368  if (fptr.Charge() < 0) {
369  checkError();
370  }
371  }
372 
373  @Override
374  protected void onPreExecute() {
375  buttonsLayout.setVisibility(View.GONE);
376  }
377 
378  @Override
379  protected void onPostExecute(Void result) {
380  buttonsLayout.setVisibility(View.VISIBLE);
381  }
382 
383  @Override
384  protected Void doInBackground(Void... params) {
385  Random random = new Random();
386  fptr = new Fptr();
387  try {
388  fptr.create(getApplication());
389 
390  publishProgress("Загрузка настроек...");
391  if (fptr.put_DeviceSettings(getSettings()) < 0) {
392  checkError();
393  }
394 
395  publishProgress("Установка соединения...");
396  if (fptr.put_DeviceEnabled(true) < 0) {
397  checkError();
398  }
399  publishProgress("OK");
400 
401  publishProgress("Проверка связи...");
402  if (fptr.GetStatus() < 0) {
403  checkError();
404  }
405  publishProgress("OK");
406 
407  // Отменяем чек, если уже открыт. Ошибки "Неверный режим" и "Чек уже закрыт"
408  // не являются ошибками, если мы хотим просто отменить чек
409  publishProgress("Отмена чека...");
410  try {
411  if (fptr.CancelCheck() < 0) {
412  checkError();
413  }
414  } catch (DriverException e) {
415  int rc = fptr.get_ResultCode();
416  if (rc != -16 && rc != -3801) {
417  throw e;
418  }
419  }
420  publishProgress("OK");
421 
422  if (PRINT_FISCAL_CHECK) {
423  publishProgress("Фискальный чек...");
424  // Открываем чек продажи, попутно обработав превышение смены
425  publishProgress("Открытие чека...");
426  try {
427  openCheck(IFptr.CHEQUE_TYPE_SELL);
428  } catch (DriverException e) {
429  // Проверка на превышение смены
430  if (fptr.get_ResultCode() == -3822) {
431  reportZ();
432  openCheck(IFptr.CHEQUE_TYPE_SELL);
433  } else {
434  throw e;
435  }
436  }
437 
438  BigDecimal sum = new BigDecimal(0);
439  for (int i = -2; i < 5; ++i) {
440  if(USE_FZ54)
441  {
442  double price = Math.pow(10, i), quantity = 1;
443  publishProgress(String.format("Регистрация %d", i + 3));
444  registrationFZ54(String.format("Позиция %d", i + 3), price, quantity, price*quantity, IFptr.TAX_VAT_18);
445  sum = sum.add(new BigDecimal(price).multiply(new BigDecimal(quantity)));
446  }
447  else {
448  double price = Math.pow(10, i), quantity = 1;
449  publishProgress(String.format("Регистрация %d", i + 3));
450  registration(String.format("Позиция %d", i + 3), price, quantity);
451  sum = sum.add(new BigDecimal(price).multiply(new BigDecimal(quantity)));
452  // Скидка на позицию
453  publishProgress("Скидка на позицию");
454  if (i % 2 == 0) {
455  discount(1, IFptr.DISCOUNT_SUMM, IFptr.DESTINATION_POSITION);
456  } else {
457  charge(1, IFptr.DISCOUNT_PERCENT, IFptr.DESTINATION_POSITION);
458  }
459  }
460  }
461  // Скидка на чек
462  publishProgress("Скидка на чек");
463  if (USE_FZ54) {
464  // Можно сбрасывать в пределах копеек. При подаче 0 копейки отбрасываются полностью
465  discount(0, IFptr.DISCOUNT_SUMM, IFptr.DESTINATION_CHECK);
466  }
467  else {
468  discount(1, IFptr.DISCOUNT_PERCENT, IFptr.DESTINATION_CHECK);
469  }
470 
471  // Оплачиваем
472  publishProgress("Оплата...");
473  payment(sum.divide(new BigDecimal(4)).doubleValue(), 1);
474  payment(sum.divide(new BigDecimal(4)).doubleValue(), 2);
475  payment(sum.divide(new BigDecimal(4)).doubleValue(), 3);
476  payment(sum.doubleValue(), 0);
477  // Закрываем чек
478  publishProgress("Закрытие чека");
479  closeCheck(0);
480  }
481 
482  if (PRINT_NONFISCAL_CHECK) {
483  publishProgress("Печать строк");
484  publishProgress("Нефискальный чек...");
485  printText("Я сразу смазал карту будня, плеснувши краску из стакана;\n"
486  + "Я показал на блюде студня косые скулы океана.\n"
487  + "На чешуе жестяной рыбы прочел я зовы новых губ.", IFptr.ALIGNMENT_LEFT, IFptr.WRAP_WORD);
488  printText("А вы", IFptr.ALIGNMENT_LEFT, IFptr.WRAP_WORD);
489  printText("ноктюрн сыграть", IFptr.ALIGNMENT_CENTER, IFptr.WRAP_WORD);
490  printText("могли бы", IFptr.ALIGNMENT_RIGHT, IFptr.WRAP_WORD);
491  printText("на флейте водосточных труб?", IFptr.ALIGNMENT_LEFT, IFptr.WRAP_WORD);
492  publishProgress("OK");
493 
494  publishProgress("Печать ШК");
495  printText("\nEAN8", IFptr.ALIGNMENT_CENTER, IFptr.WRAP_LINE);
496  printBarcode(IFptr.BARCODE_TYPE_EAN8, "40182735", 100);
497  printText("");
498  printText("\nEAN13", IFptr.ALIGNMENT_CENTER, IFptr.WRAP_LINE);
499  printBarcode(IFptr.BARCODE_TYPE_EAN13, "4007630000116", 200);
500  printText("");
501  printText("\nUPCA", IFptr.ALIGNMENT_CENTER, IFptr.WRAP_LINE);
502  printBarcode(IFptr.BARCODE_TYPE_UPCA, "697929110035", 100);
503  printText("");
504  printText("\nCODE39", IFptr.ALIGNMENT_CENTER, IFptr.WRAP_LINE);
505  printBarcode(IFptr.BARCODE_TYPE_CODE39, "ATOL.RU", 100);
506  printText("");
507  printText("\nPDF417", IFptr.ALIGNMENT_CENTER, IFptr.WRAP_LINE);
508  printBarcode(IFptr.BARCODE_TYPE_PDF417, "1234567", 200);
509  printText("");
510  printText("\nQR", IFptr.ALIGNMENT_CENTER, IFptr.WRAP_LINE);
511  printBarcode(IFptr.BARCODE_TYPE_QRCODE, "АТОЛ.РУ", 500);
512  printText("");
513  printText("\nITF-14", IFptr.ALIGNMENT_CENTER, IFptr.WRAP_LINE);
514  printBarcode(IFptr.BARCODE_TYPE_ITF14, "00012345600012", 100);
515  printText("");
516  printText("\nInterleaved 2 of 5", IFptr.ALIGNMENT_CENTER, IFptr.WRAP_LINE);
517  printBarcode(IFptr.BARCODE_TYPE_INTERLEAVED_2_OF_5, "04062300106659", 100);
518  printText("");
519  printFooter();
520  publishProgress("OK");
521  }
522  } catch (Exception e) {
523  publishProgress(e.toString());
524  } finally {
525  fptr.destroy();
526  }
527  return null;
528  }
529 
530  @Override
531  protected void onProgressUpdate(String... values) {
532  if (values == null || values.length == 0) {
533  return;
534  }
535  logAdd(values[0]);
536  }
537 
538  };
539  task.execute();
540  }
541  });
542 
543  }
544 
545  @Override
546  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
547  if (requestCode == REQUEST_SHOW_SETTINGS) {
548  if (data != null && data.getExtras() != null) {
549  String settings = data.getExtras().getString(SettingsActivity.DEVICE_SETTINGS);
550  setSettings(settings);
551  }
552  }
553  }
554 
555  private String getSettings() {
556  return preferences.getString(SettingsActivity.DEVICE_SETTINGS, getDefaultSettings());
557  }
558 
559  private void setSettings(String settings) {
560  SharedPreferences.Editor editor = preferences.edit();
561  editor.putString(SettingsActivity.DEVICE_SETTINGS, settings);
562  editor.apply();
563  }
564 
565  private String getDefaultSettings() {
566  IFptr fprint = new Fptr();
567  fprint.create(this);
568  String settings = fprint.get_DeviceSettings();
569  fprint.destroy();
570  return settings;
571  }
572 
573  private void logAdd(String string) {
574  String value = (String) log.getText();
575  if (value.length() > 2096) {
576  value = value.substring(0, 2096);
577  }
578  log.setText(string + "\n" + value);
579  }
580 
581  private static class DriverException extends Exception {
582  public DriverException(String msg) {
583  super(msg);
584  }
585  }
586 }