diff --git a/lib/core/models/dictionary/good_response.dart b/lib/core/models/dictionary/good_response.dart index 0865f46..a24c298 100644 --- a/lib/core/models/dictionary/good_response.dart +++ b/lib/core/models/dictionary/good_response.dart @@ -1,3 +1,5 @@ +import 'package:satu/core/utils/utils_parse.dart'; + /// id : 6 /// category_id : 4 /// name : "KENT SILVER" @@ -17,7 +19,7 @@ class GoodResponse { int? articul; int? price; int? optPrice; - int? basePrice; + double? basePrice; int? divisible; String? updatedAt; @@ -30,7 +32,7 @@ class GoodResponse { goodResponseBean.articul = map['articul'] as int; goodResponseBean.price = map['price'] as int; goodResponseBean.optPrice = map['opt_price'] as int; - goodResponseBean.basePrice = map['base_price'] as int; + goodResponseBean.basePrice = cast(map['base_price']); goodResponseBean.divisible = map['divisible'] as int; goodResponseBean.updatedAt = map['updated_at'] as String; return goodResponseBean; diff --git a/lib/core/models/settings/printer_setting.dart b/lib/core/models/settings/printer_setting.dart new file mode 100644 index 0000000..1590594 --- /dev/null +++ b/lib/core/models/settings/printer_setting.dart @@ -0,0 +1,73 @@ + +import 'package:satu/core/utils/utils_parse.dart'; + +class PrinterConst { + PrinterConst(); + static const String paperSize58mm = '58mm'; + static const String paperSize80mm = '80mm'; + static const String encodingCP866 = 'CP866'; + static const String encodingCP1251 = 'Windows-1251'; + static const String encodingBigEncoding = 'BigEncoding'; +} + +class PrinterSetting { + + PrinterSetting({ + this.device, + this.encoding = PrinterConst.encodingCP866, + this.paperSize = PrinterConst.paperSize58mm, + }); + + PrinterDevice? device; + String? encoding ; + String? paperSize ; + + dynamic toMap() { + return { + 'device': device != null ? device!.toMap() : null, + 'encoding': encoding, + 'paperSize': paperSize, + }; + } + + factory PrinterSetting.fromMap(dynamic map) { + return PrinterSetting( + device: map['device']!=null ? PrinterDevice.fromMap(map['device']) : null, + encoding: cast(map['encoding']), + paperSize: cast(map['paperSize']), + ); + } + +} + +class PrinterDevice { + String? name; + String? address; + int? type = 0; + bool? connected = false; + + PrinterDevice({ + this.name, + this.address, + this.type, + this.connected, + }); + + dynamic toMap() { + return { + 'name': name, + 'address': address, + 'type': type, + 'connected': connected, + }; + } + + factory PrinterDevice.fromMap(dynamic map) { + return PrinterDevice( + name: cast(map['name']), + address: cast(map['address']), + type: cast(map['type']), + connected: cast(map['connected']), + ); + } +} \ No newline at end of file diff --git a/lib/core/redux/actions/setting_actions.dart b/lib/core/redux/actions/setting_actions.dart new file mode 100644 index 0000000..a216304 --- /dev/null +++ b/lib/core/redux/actions/setting_actions.dart @@ -0,0 +1,67 @@ +import 'dart:convert'; + +import 'package:intl/intl.dart'; +import 'package:logger/logger.dart'; +import 'package:meta/meta.dart'; +import 'package:redux/redux.dart'; +import 'package:redux_thunk/redux_thunk.dart'; +import 'package:satu/core/entity/category_entity.dart'; +import 'package:satu/core/entity/goods_entity.dart'; +import 'package:satu/core/entity/transaction_entity.dart'; +import 'package:satu/core/entity/transaction_rec_entity.dart'; +import 'package:satu/core/models/entity_data/transaction_data.dart'; +import 'package:satu/core/models/flow/dao/product_dao.dart'; +import 'package:satu/core/models/flow/dao/transaction_dao.dart'; +import 'package:satu/core/models/flow/transaction_state.dart'; +import 'package:satu/core/models/settings/printer_setting.dart'; +import 'package:satu/core/redux/state/journal_state.dart'; +import 'package:satu/core/redux/state/sell_state.dart'; +import 'package:satu/core/redux/state/setting_state.dart'; +import 'package:satu/core/services/db_service.dart'; +import 'package:satu/core/utils/locator.dart'; +import 'package:satu/core/utils/logger.dart'; +import 'package:uuid/uuid.dart'; + +import '../store.dart'; + +@immutable +class SetSettingStateAction { + const SetSettingStateAction(this.settingState); + + final SettingState settingState; +} + +final Logger log = getLogger('SetSettingStateAction'); + + +ThunkAction selectBluetoothDevice(PrinterDevice device) { + return (Store store) async { + final PrinterSetting? setting = store.state.settingState?.printer; + if(setting != null) { + setting.device = device; + store.dispatch(SetSettingStateAction(SettingState(printer: setting))); + log.i('device with name ${device.name} added'); + } + }; +} + +ThunkAction setPaperSize(String size) { + return (Store store) async { + final PrinterSetting? setting = store.state.settingState?.printer; + if(setting != null) { + setting.paperSize = size; + store.dispatch(SetSettingStateAction(SettingState(printer: setting))); + } + }; +} + +ThunkAction setEncodingPrint(String encoding) { + return (Store store) async { + final PrinterSetting? setting = store.state.settingState?.printer; + if(setting != null) { + setting.encoding = encoding; + store.dispatch(SetSettingStateAction(SettingState(printer: setting))); + } + }; +} + diff --git a/lib/core/redux/reducers/setting_reducer.dart b/lib/core/redux/reducers/setting_reducer.dart new file mode 100644 index 0000000..64df633 --- /dev/null +++ b/lib/core/redux/reducers/setting_reducer.dart @@ -0,0 +1,14 @@ +import 'package:satu/core/redux/actions/journal_actions.dart'; +import 'package:satu/core/redux/actions/sell_actions.dart'; +import 'package:satu/core/redux/actions/setting_actions.dart'; +import 'package:satu/core/redux/actions/user_actions.dart'; +import 'package:satu/core/redux/state/journal_state.dart'; +import 'package:satu/core/redux/state/sell_state.dart'; +import 'package:satu/core/redux/state/setting_state.dart'; +import 'package:satu/core/redux/state/user_state.dart'; + +SettingState settingReducer( + SettingState prevState, SetSettingStateAction action) { + final SettingState payload = action.settingState; + return prevState.copyWith(printer: payload.printer); +} diff --git a/lib/core/redux/state/setting_state.dart b/lib/core/redux/state/setting_state.dart new file mode 100644 index 0000000..d918017 --- /dev/null +++ b/lib/core/redux/state/setting_state.dart @@ -0,0 +1,32 @@ +import 'package:meta/meta.dart'; +import 'package:satu/core/models/flow/dao/transaction_dao.dart'; +import 'package:satu/core/models/settings/printer_setting.dart'; + +@immutable +class SettingState { + const SettingState({this.printer}); + + factory SettingState.initial(SettingState? settingState) => + SettingState(printer: settingState?.printer ?? PrinterSetting()); + + final PrinterSetting? printer; + + SettingState copyWith({PrinterSetting? printer}) { + return SettingState(printer: printer ?? this.printer); + } + + dynamic toMap() { + return { + 'printer': printer !=null ? printer!.toMap() : null, + }; + } + + factory SettingState.fromMap(dynamic map) { + if (map == null) return SettingState.initial(null); + return SettingState( + printer: map['printer'] != null + ? PrinterSetting.fromMap(map['printer']) + : null, + ); + } +} diff --git a/lib/core/redux/store.dart b/lib/core/redux/store.dart index f88da07..0c653aa 100644 --- a/lib/core/redux/store.dart +++ b/lib/core/redux/store.dart @@ -6,13 +6,16 @@ import 'package:redux_persist/redux_persist.dart'; import 'package:satu/core/redux/actions/journal_actions.dart'; import 'package:satu/core/redux/actions/nav_actions.dart'; import 'package:satu/core/redux/actions/sell_actions.dart'; +import 'package:satu/core/redux/actions/setting_actions.dart'; import 'package:satu/core/redux/reducers/journal_reducer.dart'; import 'package:satu/core/redux/reducers/nav_reducer.dart'; import 'package:satu/core/redux/reducers/sell_reducer.dart'; +import 'package:satu/core/redux/reducers/setting_reducer.dart'; import 'package:satu/core/redux/reducers/user_reducer.dart'; import 'package:satu/core/redux/state/journal_state.dart'; import 'package:satu/core/redux/state/nav_state.dart'; import 'package:satu/core/redux/state/sell_state.dart'; +import 'package:satu/core/redux/state/setting_state.dart'; import 'package:satu/core/redux/state/user_state.dart'; import 'actions/user_actions.dart'; @@ -20,21 +23,20 @@ import 'actions/user_actions.dart'; //reducer context AppState appReducer(AppState state, dynamic action) { if (action is SetUserStateAction) { - /** UserAction **/ final UserState nextState = userReducer(state.userState!, action); return state.copyWith(userState: nextState); } else if (action is SetNavStateAction) { - /** NavAction **/ final NavState nextState = navReducer(state.navState!, action); return state.copyWith(navState: nextState); } else if (action is SetSellStateAction) { - /** NavAction **/ final SellState nextState = sellReducer(state.sellState!, action); return state.copyWith(sellState: nextState); } else if (action is SetJournalStateAction) { - /** NavAction **/ final JournalState nextState = journalReducer(state.journalState!, action); return state.copyWith(journalState: nextState); + } else if (action is SetSettingStateAction) { + final SettingState nextState = settingReducer(state.settingState!, action); + return state.copyWith(settingState: nextState); } return state; } @@ -47,12 +49,14 @@ class AppState { this.navState, this.sellState, this.journalState, + this.settingState, }); final UserState? userState; final NavState? navState; final SellState? sellState; final JournalState? journalState; + final SettingState? settingState; //stable work AppState copyWith({ @@ -60,12 +64,14 @@ class AppState { NavState? navState, SellState? sellState, JournalState? journalState, + SettingState? settingState, }) { return AppState( userState: userState ?? this.userState, navState: navState ?? this.navState, sellState: sellState ?? this.sellState, journalState: journalState ?? this.journalState, + settingState: settingState ?? this.settingState, ); } @@ -73,6 +79,7 @@ class AppState { return json != null ? AppState( userState: UserState.fromJson(json['userState']), + settingState: SettingState.fromMap(json['settingState']), ) : null; } @@ -80,6 +87,7 @@ class AppState { dynamic toJson() { return { 'userState': userState!.toJson(), + 'settingState': settingState!.toMap(), }; } } @@ -112,14 +120,18 @@ class Redux { final navStateInitial = NavState.initial(); final sellStateInitial = SellState.initial(); final journalStateInitial = JournalState.initial(); + final settingStateInitial = SettingState.initial(initialState?.settingState); - _store = Store(appReducer, - middleware: [thunkMiddleware, persist.createMiddleware()], - initialState: AppState( - userState: userStateInitial, - navState: navStateInitial, - sellState: sellStateInitial, - journalState: journalStateInitial, - )); + _store = Store( + appReducer, + middleware: [thunkMiddleware, persist.createMiddleware()], + initialState: AppState( + userState: userStateInitial, + navState: navStateInitial, + sellState: sellStateInitial, + journalState: journalStateInitial, + settingState: settingStateInitial, + ), + ); } } diff --git a/lib/core/utils/pos_printer.dart b/lib/core/utils/pos_printer.dart index 2e0380f..2ff2974 100644 --- a/lib/core/utils/pos_printer.dart +++ b/lib/core/utils/pos_printer.dart @@ -1,25 +1,37 @@ import 'dart:typed_data'; import 'package:charset_converter/charset_converter.dart'; +import 'package:esc_pos_bluetooth/esc_pos_bluetooth.dart'; import 'package:esc_pos_utils/esc_pos_utils.dart'; import 'package:flutter/services.dart'; -import 'dart:io'; +import 'package:flutter_bluetooth_basic/flutter_bluetooth_basic.dart'; import 'package:image/image.dart'; +import 'package:satu/core/models/settings/printer_setting.dart'; - - -Future> getReceipt() async { +Future> getReceipt(String encoding, String paperSize) async { final profile = await CapabilityProfile.load(); - final generator = Generator(PaperSize.mm80, profile); - List bytes = []; - generator.setGlobalCodeTable('CP866'); - Uint8List firstCol = await CharsetConverter.encode('cp866', 'Русский'); + final generator = Generator( + paperSize == PrinterConst.paperSize58mm ? PaperSize.mm58 : PaperSize.mm80, + profile, + ); - bytes += generator.textEncoded(firstCol, styles: const PosStyles(align: PosAlign.left)); + String codeTable = 'CP866'; + if(encoding == PrinterConst.encodingCP866) { + codeTable = 'CP866'; + } else if(encoding == PrinterConst.encodingCP1251) { + codeTable = 'CP1251'; + } + + + List bytes = []; + generator.setGlobalCodeTable(codeTable); + final Uint8List firstCol = + await CharsetConverter.encode(encoding.toLowerCase(), 'Тестовый чек'); + bytes += generator.textEncoded(firstCol); bytes += - generator.text('Align center', styles: const PosStyles(align: PosAlign.center)); - bytes += generator.text('Align right', + generator.text('CENTER', styles: const PosStyles(align: PosAlign.center)); + bytes += generator.text('Right', styles: const PosStyles(align: PosAlign.right), linesAfter: 1); bytes += generator.row([ @@ -40,27 +52,32 @@ Future> getReceipt() async { ), ]); - // bytes += generator.text('Text size 200%', - // styles: const PosStyles( - // height: PosTextSize.size2, - // width: PosTextSize.size2, - // )); - // - // // Print barcode - // final List barData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 4]; - // bytes += generator.barcode(Barcode.upcA(barData)); + bytes += generator.text( + 'Text size 200%', + styles: const PosStyles( + height: PosTextSize.size2, + width: PosTextSize.size2, + ), + ); + + // Print barcode + final List barData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 4]; + bytes += generator.barcode(Barcode.upcA(barData)); bytes += generator.feed(2); bytes += generator.cut(); return bytes; } -Future> getReceiptImg() async { +Future> getReceiptImg(String paperSize) async { final profile = await CapabilityProfile.load(); - final generator = Generator(PaperSize.mm80, profile); + final generator = Generator( + paperSize == PrinterConst.paperSize58mm ? PaperSize.mm58 : PaperSize.mm80, + profile, + ); List bytes = []; - generator.setGlobalCodeTable('CP866'); - final ByteData data = await rootBundle.load('assets/images/aman_kassa_check.png') as ByteData; + final ByteData data = + await rootBundle.load('assets/images/aman_kassa_check.png'); final Uint8List imgBytes = data.buffer.asUint8List(); final Image? image = decodeImage(imgBytes); // Using `ESC *` @@ -68,4 +85,19 @@ Future> getReceiptImg() async { bytes += generator.feed(2); bytes += generator.cut(); return bytes; -} \ No newline at end of file +} + +BluetoothDevice printerDeviceToBluetoothDevice(PrinterDevice device) { + return BluetoothDevice() + ..name = device.name + ..address = device.address + ..connected = device.connected + ..type = device.type; +} + +PrinterDevice bluetoothDeviceToPrinterDevice(PrinterBluetooth device) { + return PrinterDevice() + ..name = device.name + ..address = device.address + ..type = device.type; +} diff --git a/lib/main.dart b/lib/main.dart index 80cfe63..a38a845 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -37,22 +37,27 @@ class MainApplication extends StatelessWidget { return StoreProvider( store: Redux.store!, child: ScreenUtilInit( - designSize: Size(375, 812), + designSize: const Size( + 375, + 812, + ), builder: () => MaterialApp( theme: ThemeData( - backgroundColor: backgroundColor, - primaryColor: whiteColor, - accentColor: primaryColor, - scaffoldBackgroundColor: backgroundColor - // textTheme: GoogleFonts.robotoTextTheme( - // Theme.of(context).textTheme, - // ) - ), + backgroundColor: backgroundColor, + primaryColor: whiteColor, + scaffoldBackgroundColor: backgroundColor, + colorScheme: + ColorScheme.fromSwatch().copyWith(secondary: primaryColor), + // textTheme: GoogleFonts.robotoTextTheme( + // Theme.of(context).textTheme, + // ) + ), debugShowCheckedModeBanner: false, builder: (context, child) => Navigator( key: locator().dialogNavigationKey, onGenerateRoute: (settings) => MaterialPageRoute( - builder: (context) => DialogManager(child: child!)), + builder: (context) => DialogManager(child: child!), + ), ), navigatorKey: locator().navigatorKey, home: StartUpView(), diff --git a/lib/routes/route_names.dart b/lib/routes/route_names.dart index c9b4ecb..a8451e2 100644 --- a/lib/routes/route_names.dart +++ b/lib/routes/route_names.dart @@ -1,23 +1,29 @@ +// login const String loginViewRoute = 'LoginView'; +// main const String mainViewRoute = 'MainView'; + +// work - tabs page const String workViewRoute = 'WorkView'; const String addProductViewRoute = 'AddProductView'; const String addByBarcodeViewRoute = 'AddByBarcodeView'; - -const String contragentSelectViewRoute = 'ContragentSelectViewRoute'; - const String paymentViewRoute = 'paymentViewRoute'; const String receiptViewRoute = 'receiptViewRoute'; -const String settingPrinterBluetoothViewRoute = 'SettingPrinterBluetoothView'; - - -// Generate the views here +// dictionaries - category const String categoryEditRoute = 'categoryEditRoute'; const String categorySelectViewRoute = 'categorySelectViewRoute'; - +// dictionaries - good const String goodsEditRoute = 'goodsEditRoute'; const String goodsDictionaryViewRoute = 'goodsDictionaryViewRoute'; +//dictionaries - contragent +const String contragentSelectViewRoute = 'ContragentSelectViewRoute'; + +// setting - ble printer +const String settingPrinterBluetoothViewRoute = 'SettingPrinterBluetoothView'; +const String settingPrinterBluetoothSelectViewRoute = 'settingPrinterBluetoothSelectViewRoute'; +const String settingPrinterPaperSizeViewRoute = 'settingPrinterPaperSizeViewRoute'; +const String settingPrinterEncodingViewRoute = 'settingPrinterEncodingViewRoute'; diff --git a/lib/routes/router.dart b/lib/routes/router.dart index 2396f62..4bd4647 100644 --- a/lib/routes/router.dart +++ b/lib/routes/router.dart @@ -1,4 +1,3 @@ - import 'package:flutter/material.dart'; import 'package:satu/core/models/dictionary/category_row_data.dart'; import 'package:satu/core/models/dictionary/good_row_data.dart'; @@ -8,6 +7,9 @@ import 'package:satu/views/dictionaries/category/category_select_view.dart'; import 'package:satu/views/dictionaries/goods/goods_edit.dart'; import 'package:satu/views/login/login_view.dart'; import 'package:satu/views/main/main_view.dart'; +import 'package:satu/views/settings/printer_bluetooth/printer_encoding_select.dart'; +import 'package:satu/views/settings/printer_bluetooth/printer_paper_size_select.dart'; +import 'package:satu/views/settings/printer_bluetooth/printer_select.dart'; import 'package:satu/views/settings/printer_bluetooth/printer_view.dart'; import 'package:satu/views/work/views/add_by_barcode/add_by_barcode_view.dart'; import 'package:satu/views/work/views/add_product/add_product_view.dart'; @@ -23,60 +25,79 @@ Route generateRoute(RouteSettings settings) { case loginViewRoute: //LoginModel model = settings.arguments as LoginModel; return _getPageRoute( - routeName: settings.name!, + routeName: settings.name, viewToShow: LoginView(), ); case workViewRoute: return _getPageRoute( - routeName: settings.name!, - viewToShow: WorkView(), + routeName: settings.name, + viewToShow: const WorkView(), ); case mainViewRoute: return _getPageRoute( - routeName: settings.name!, + routeName: settings.name, viewToShow: MainView(), ); case addProductViewRoute: return _getPageRoute( - routeName: settings.name!, + routeName: settings.name, viewToShow: AddProductView(), ); case addByBarcodeViewRoute: return _getPageRoute( - routeName: settings.name!, - viewToShow: AddByBarcodeView(), + routeName: settings.name, + viewToShow: const AddByBarcodeView(), ); case settingPrinterBluetoothViewRoute: return _getPageRoute( - routeName: settings.name!, + routeName: settings.name, viewToShow: const PrinterView(), ); + case settingPrinterBluetoothSelectViewRoute: + return _getPageRoute( + routeName: settings.name, + viewToShow: const PrinterSelect(), + ); + case settingPrinterPaperSizeViewRoute: + return _getPageRoute( + routeName: settings.name, + viewToShow: const PrinterPaperSizeView(), + ); + case settingPrinterEncodingViewRoute: + return _getPageRoute( + routeName: settings.name, + viewToShow: const PrinterEncodingView(), + ); case contragentSelectViewRoute: return _getPageRoute( - routeName: settings.name!, + routeName: settings.name, viewToShow: SelectContragentView(), ); case paymentViewRoute: return _getPageRoute( - routeName: settings.name!, + routeName: settings.name, viewToShow: const PaymentView(), ); case categoryEditRoute: final CategoryRowDao category = settings.arguments! as CategoryRowDao; return _getPageRoute( - routeName: settings.name!, - viewToShow: CategoryEdit(category: category,), + routeName: settings.name, + viewToShow: CategoryEdit( + category: category, + ), ); case categorySelectViewRoute: return _getPageRoute( - routeName: settings.name!, + routeName: settings.name, viewToShow: CategorySelectView(), ); case goodsEditRoute: final GoodRowDao good = settings.arguments! as GoodRowDao; return _getPageRoute( - routeName: settings.name!, - viewToShow: GoodEdit(good: good,), + routeName: settings.name, + viewToShow: GoodEdit( + good: good, + ), ); case receiptViewRoute: @@ -84,7 +105,9 @@ Route generateRoute(RouteSettings settings) { //return SlideRightRoute(widget: ImageShowContainer(data)); return _getPageRoute( routeName: settings.name, - viewToShow: ReceiptView(transactionData: data,), + viewToShow: ReceiptView( + transactionData: data, + ), ); default: return MaterialPageRoute( @@ -104,7 +127,6 @@ PageRoute _getPageRoute({String? routeName, Widget? viewToShow}) { } class SlideRightRoute extends PageRouteBuilder { - final Widget? widget; SlideRightRoute({this.widget}) : super( pageBuilder: (BuildContext context, Animation animation, @@ -115,8 +137,8 @@ class SlideRightRoute extends PageRouteBuilder { Animation animation, Animation secondaryAnimation, Widget child) { - return new SlideTransition( - position: new Tween( + return SlideTransition( + position: Tween( begin: const Offset(1.0, 0.0), end: Offset.zero, ).animate(animation), @@ -124,4 +146,5 @@ class SlideRightRoute extends PageRouteBuilder { ); }, ); + final Widget? widget; } diff --git a/lib/views/settings/printer_bluetooth/printer_encoding_select.dart b/lib/views/settings/printer_bluetooth/printer_encoding_select.dart new file mode 100644 index 0000000..064635d --- /dev/null +++ b/lib/views/settings/printer_bluetooth/printer_encoding_select.dart @@ -0,0 +1,58 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_redux/flutter_redux.dart'; +import 'package:satu/core/models/settings/printer_setting.dart'; +import 'package:satu/core/redux/actions/setting_actions.dart'; +import 'package:satu/core/redux/store.dart'; +import 'package:satu/widgets/bar/products_app_bar.dart'; +import 'package:satu/widgets/bar/products_title_bar.dart'; +import 'package:satu/widgets/fields/line_checkbox.dart'; + +class PrinterEncodingView extends StatelessWidget { + const PrinterEncodingView({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: const ProductsAppBar( + title: 'Кодировка печати', + ), + body: StoreConnector( + converter: (store) => store.state.settingState!.printer!, + builder: (context, printer) { + return Column(children: [ + const ProductsTitleBarBar(title: 'Выберите кодировку принтера'), + LineCheckBox( + PrinterConst.encodingCP866, + value: printer.encoding == PrinterConst.encodingCP866, + onTap: () => { + Redux.store!.dispatch( + setEncodingPrint(PrinterConst.encodingCP866), + ) + }, + ), + const Divider(height: 1,), + LineCheckBox( + PrinterConst.encodingCP1251, + value: printer.encoding == PrinterConst.encodingCP1251, + onTap: () => { + Redux.store!.dispatch( + setEncodingPrint(PrinterConst.encodingCP1251), + ) + }, + ), + const Divider(height: 1,), + LineCheckBox( + PrinterConst.encodingBigEncoding, + value: printer.encoding == PrinterConst.encodingBigEncoding, + onTap: () => { + Redux.store!.dispatch( + setEncodingPrint(PrinterConst.encodingBigEncoding), + ) + }, + ), + ]); + } + ), + ); + } +} diff --git a/lib/views/settings/printer_bluetooth/printer_paper_size_select.dart b/lib/views/settings/printer_bluetooth/printer_paper_size_select.dart new file mode 100644 index 0000000..ad37447 --- /dev/null +++ b/lib/views/settings/printer_bluetooth/printer_paper_size_select.dart @@ -0,0 +1,48 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_redux/flutter_redux.dart'; +import 'package:satu/core/models/settings/printer_setting.dart'; +import 'package:satu/core/redux/actions/setting_actions.dart'; +import 'package:satu/core/redux/store.dart'; +import 'package:satu/widgets/bar/products_app_bar.dart'; +import 'package:satu/widgets/bar/products_title_bar.dart'; +import 'package:satu/widgets/fields/line_checkbox.dart'; + +class PrinterPaperSizeView extends StatelessWidget { + const PrinterPaperSizeView({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: const ProductsAppBar( + title: 'Размер чека', + ), + body: StoreConnector( + converter: (store) => store.state.settingState!.printer!, + builder: (context, printer) { + return Column(children: [ + const ProductsTitleBarBar(title: 'Выберите размер чека'), + LineCheckBox( + PrinterConst.paperSize58mm, + value: printer.paperSize == PrinterConst.paperSize58mm, + onTap: () => { + Redux.store!.dispatch( + setPaperSize(PrinterConst.paperSize58mm), + ) + }, + ), + const Divider(height: 1,), + LineCheckBox( + PrinterConst.paperSize80mm, + value: printer.paperSize == PrinterConst.paperSize80mm, + onTap: () => { + Redux.store!.dispatch( + setPaperSize(PrinterConst.paperSize80mm), + ) + }, + ), + ]); + } + ), + ); + } +} diff --git a/lib/views/settings/printer_bluetooth/printer_select.dart b/lib/views/settings/printer_bluetooth/printer_select.dart index fb0c37d..091fd6b 100644 --- a/lib/views/settings/printer_bluetooth/printer_select.dart +++ b/lib/views/settings/printer_bluetooth/printer_select.dart @@ -2,15 +2,21 @@ import 'dart:async'; import 'dart:convert'; import 'dart:typed_data'; -import 'package:bluetooth_print/bluetooth_print.dart'; -import 'package:bluetooth_print/bluetooth_print_model.dart'; -import 'package:charset_converter/charset_converter.dart'; +// import 'package:bluetooth_print/bluetooth_print.dart'; +// import 'package:bluetooth_print/bluetooth_print_model.dart'; +import 'package:esc_pos_bluetooth/esc_pos_bluetooth.dart'; import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; +import 'package:flutter_redux/flutter_redux.dart'; import 'package:logger/logger.dart'; +import 'package:satu/core/models/settings/printer_setting.dart'; +import 'package:satu/core/redux/actions/setting_actions.dart'; +import 'package:satu/core/redux/store.dart'; import 'package:satu/core/utils/logger.dart'; import 'package:satu/core/utils/pos_printer.dart'; +import 'package:satu/widgets/bar/products_app_bar.dart'; +import 'package:satu/widgets/bar/products_title_bar.dart'; +import 'package:satu/widgets/fields/line_checkbox.dart'; class PrinterSelect extends StatefulWidget { const PrinterSelect({Key? key}) : super(key: key); @@ -21,186 +27,125 @@ class PrinterSelect extends StatefulWidget { class _PrinterSelectState extends State { final Logger log = getLogger('_PrinterViewState'); - BluetoothPrint? bluetoothPrint; - bool _connected = false; - BluetoothDevice? _device; - String tips = 'no device connect'; + //BluetoothPrint? bluetoothPrint; + // + // bool _connected = false; + // BluetoothDevice? _device; + PrinterBluetoothManager printerManager = PrinterBluetoothManager(); + List _devices = []; @override void initState() { - bluetoothPrint = BluetoothPrint.instance; - if (WidgetsBinding.instance != null) { - WidgetsBinding.instance!.addPostFrameCallback((_) => initBluetooth()); - } + //bluetoothPrint = BluetoothPrint.instance; + // if (WidgetsBinding.instance != null) { + // WidgetsBinding.instance!.addPostFrameCallback((_) => initBluetooth()); + // } super.initState(); + + printerManager.scanResults.listen((devices) async { + // print('UI: Devices found ${devices.length}'); + setState(() { + _devices = devices; + }); + }); + _startScanDevices(); + } + + void _startScanDevices() { + setState(() { + _devices = []; + }); + printerManager.startScan(Duration(seconds: 4)); + } + + void _stopScanDevices() { + printerManager.stopScan(); } // Platform messages are asynchronous, so we initialize in an async method. - Future initBluetooth() async { - bluetoothPrint!.startScan(timeout: Duration(seconds: 4)); - - final bool isConnected = await bluetoothPrint!.isConnected ?? false; - - bluetoothPrint!.state.listen((state) { - print('cur device status: $state'); - - switch (state) { - case BluetoothPrint.CONNECTED: - setState(() { - _connected = true; - tips = 'connect success'; - }); - break; - case BluetoothPrint.DISCONNECTED: - setState(() { - _connected = false; - tips = 'disconnect success'; - }); - break; - default: - break; - } - }); - - if (!mounted) return; - - if (isConnected) { - setState(() { - _connected = true; - }); - } - } + // Future initBluetooth() async { + // bluetoothPrint!.startScan(timeout: const Duration(seconds: 4)); + // + // //final bool isConnected = await bluetoothPrint!.isConnected ?? false; + // + // // bluetoothPrint!.state.listen((state) { + // // print('cur device status: $state'); + // // + // // switch (state) { + // // case BluetoothPrint.CONNECTED: + // // setState(() { + // // _connected = true; + // // tips = 'connect success'; + // // }); + // // break; + // // case BluetoothPrint.DISCONNECTED: + // // setState(() { + // // _connected = false; + // // tips = 'disconnect success'; + // // }); + // // break; + // // default: + // // break; + // // } + // // }); + // + // if (!mounted) return; + // + // // if (isConnected) { + // // setState(() { + // // _connected = true; + // // }); + // // } + // } @override Widget build(BuildContext context) { - return MaterialApp( - home: Scaffold( - appBar: AppBar( - title: const Text('BluetoothPrint example app'), - ), - body: RefreshIndicator( - onRefresh: () => - bluetoothPrint!.startScan(timeout: Duration(seconds: 4)), - child: SingleChildScrollView( - child: Column( - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Padding( - padding: - EdgeInsets.symmetric(vertical: 10, horizontal: 10), - child: Text(tips), - ), - ], - ), - const Divider(), - StreamBuilder>( - stream: bluetoothPrint!.scanResults, - initialData: const [], - builder: (c, snapshot) => Column( - children: (snapshot.data ?? []) - .map((d) => ListTile( - title: Text(d.name ?? ''), - subtitle: Text(d.address ?? ''), - onTap: () async { - setState(() { - _device = d; - }); - }, - trailing: _device != null && - _device!.address == d.address - ? const Icon( - Icons.check, - color: Colors.green, + return Scaffold( + appBar: const ProductsAppBar( + title: 'Поиск устройства печати', + ), + body: SingleChildScrollView( + child: StoreConnector( + converter: (store) => store.state.settingState!.printer!, + builder: (context, printer) { + return Column( + children: [ + const ProductsTitleBarBar( + title: 'Выберите устройство печати'), + StreamBuilder>( + stream: printerManager.scanResults, + initialData: const [], + builder: (c, snapshot) => Column( + children: (snapshot.data ?? []) + .map( + (d) => Column( + children: [ + LineCheckBox( + d.name ?? '', + value: printer.device != null && + printer.device!.address == d.address, + onTap: () => { + Redux.store!.dispatch( + selectBluetoothDevice( + bluetoothDeviceToPrinterDevice(d), + ), ) - : null, - )) - .toList(), - ), - ), - const Divider(), - Container( - padding: EdgeInsets.fromLTRB(20, 5, 20, 10), - child: Column( - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - OutlinedButton( - onPressed: _connected - ? null - : () async { - if (_device != null && - _device!.address != null) { - await bluetoothPrint!.connect(_device!); - } else { - setState(() { - tips = 'please select device'; - }); - print('please select device'); - } }, - child: const Text('connect'), - ), - SizedBox(width: 10.0), - OutlinedButton( - onPressed: _connected - ? () async { - await bluetoothPrint!.disconnect(); - } - : null, - child: const Text('disconnect'), - ), - ], - ), - OutlinedButton( - onPressed: _connected - ? () async { - Map config = Map(); - await bluetoothPrint! - .rawBytes(config, await getReceipt()); - } - : null, - child: const Text('print receipt(esc) - text'), - ), - OutlinedButton( - onPressed: _connected - ? () async { - Map config = Map(); - await bluetoothPrint! - .rawBytes(config, await getReceiptImg()); - } - : null, - child: const Text('print label(esc) img'), - ), - ], + ), + const Divider( + height: 1, + ), + ], + ), + ) + .toList(), + ), ), - ) - ], - ), - ), - ), - floatingActionButton: StreamBuilder( - stream: bluetoothPrint!.isScanning, - initialData: false, - builder: (c, snapshot) { - if (snapshot.data != null) { - return FloatingActionButton( - onPressed: () => bluetoothPrint!.stopScan(), - backgroundColor: Colors.red, - child: const Icon(Icons.stop), + ], ); - } else { - return FloatingActionButton( - child: const Icon(Icons.search), - onPressed: () => bluetoothPrint! - .startScan(timeout: const Duration(seconds: 4))); - } - }, - ), + }), ), ); } diff --git a/lib/views/settings/printer_bluetooth/printer_view.dart b/lib/views/settings/printer_bluetooth/printer_view.dart index 8b1a293..54581c0 100644 --- a/lib/views/settings/printer_bluetooth/printer_view.dart +++ b/lib/views/settings/printer_bluetooth/printer_view.dart @@ -1,8 +1,18 @@ +import 'dart:io'; + +import 'package:esc_pos_bluetooth/esc_pos_bluetooth.dart'; import 'package:flutter/material.dart'; +import 'package:flutter_redux/flutter_redux.dart'; +import 'package:satu/core/models/settings/printer_setting.dart'; +import 'package:satu/core/redux/store.dart'; +import 'package:satu/core/services/dialog_service.dart'; +import 'package:satu/core/services/navigator_service.dart'; +import 'package:satu/core/utils/locator.dart'; +import 'package:satu/core/utils/pos_printer.dart'; +import 'package:satu/routes/route_names.dart'; import 'package:satu/shared/app_colors.dart'; import 'package:satu/shared/ui_helpers.dart'; import 'package:satu/widgets/bar/products_app_bar.dart'; -import 'package:satu/widgets/bar/products_title_bar.dart'; import 'package:satu/widgets/fields/line_tile.dart'; class PrinterView extends StatefulWidget { @@ -13,49 +23,127 @@ class PrinterView extends StatefulWidget { } class _PrinterViewState extends State { + final NavigatorService _navigatorService = locator(); + final DialogService _dialogService = locator(); + PrinterBluetoothManager printerManager = PrinterBluetoothManager(); + + bool printerLocked = false; + @override void initState() { super.initState(); } + void printTest() async { + setState(() { + printerLocked = true; + }); + try { + PrinterSetting printerSetting = Redux.store!.state.settingState!.printer!; + printerManager.selectPrinter( + PrinterBluetooth( + printerDeviceToBluetoothDevice(printerSetting.device!), + ), + ); + + bool isIos = Platform.isIOS; + int chunkSizeBytes = 3096; + int queueSleepTimeMs = 100; + + if (isIos) { + chunkSizeBytes = 75; + queueSleepTimeMs = 10; + } + + if(PrinterConst.encodingBigEncoding == printerSetting.encoding ) { + PosPrintResult printResult = await printerManager.writeBytes( + await getReceiptImg( + printerSetting.paperSize!, + ), + chunkSizeBytes: chunkSizeBytes, + queueSleepTimeMs: queueSleepTimeMs, + ); + if(printResult.value != 1) { + _dialogService.showDialog(description: printResult.msg); + } + } else { + PosPrintResult printResult = await printerManager.writeBytes( + await getReceipt( + printerSetting.encoding!, + printerSetting.paperSize!, + ), + chunkSizeBytes: chunkSizeBytes, + queueSleepTimeMs: queueSleepTimeMs, + ); + if(printResult.value != 1) { + _dialogService.showDialog(description: printResult.msg); + } + } + } finally { + await Future.delayed(const Duration(seconds: 7)); + setState(() { + printerLocked = false; + }); + } + } + @override Widget build(BuildContext context) { return Scaffold( appBar: ProductsAppBar( title: 'Принтер', actions: [ - IconButton( - onPressed: () {}, - icon: const Icon( - Icons.print, - color: placeholderColor, - ), + StoreConnector( + converter: (store) => store.state.settingState!.printer!, + builder: (context, snapshot) { + final bool success = + snapshot.device != null && printerLocked == false; + return IconButton( + onPressed: success ? printTest : null, + icon: Icon( + Icons.print, + color: success ? textColor : placeholderColor, + ), + ); + }, ), ], ), body: SingleChildScrollView( - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - verticalSpaceSmall, - LineTile( - 'Устройство не выбрано', - onTap: () {}, - labelText: 'Устройство печати', - ), - verticalSpaceSmall, - LineTile( - 'Размер не указан', - onTap: () {}, - labelText: 'Размер чека', - ), - verticalSpaceSmall, - LineTile( - 'Кодировка не указана', - onTap: () {}, - labelText: 'Кодировка печати', - ), - ], + child: StoreConnector( + converter: (store) => store.state.settingState!.printer!, + builder: (context, printer) { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + verticalSpaceSmall, + LineTile( + printer.device?.name ?? 'Устройство не выбрано', + onTap: () { + _navigatorService + .push(settingPrinterBluetoothSelectViewRoute); + }, + labelText: 'Устройство печати', + ), + verticalSpaceSmall, + LineTile( + printer.paperSize ?? 'Размер не указан', + onTap: () { + _navigatorService.push(settingPrinterPaperSizeViewRoute); + }, + labelText: 'Размер чека', + ), + verticalSpaceSmall, + LineTile( + printer.encoding ?? 'Кодировка не указана', + onTap: () { + _navigatorService.push(settingPrinterEncodingViewRoute); + }, + labelText: 'Кодировка печати', + ), + ], + ); + }, ), ), ); diff --git a/pubspec.lock b/pubspec.lock index eb9d1d6..f5fda5d 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -43,13 +43,6 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "3.0.0-nullsafety.0" - bluetooth_print: - dependency: "direct main" - description: - path: "../bluetooth_print" - relative: true - source: path - version: "3.0.1" boolean_selector: dependency: transitive description: @@ -134,6 +127,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "2.0.3" + esc_pos_bluetooth: + dependency: "direct main" + description: + name: esc_pos_bluetooth + url: "https://pub.dartlang.org" + source: hosted + version: "0.4.1" esc_pos_utils: dependency: "direct main" description: @@ -162,25 +162,18 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "6.1.2" - fixnum: - dependency: transitive - description: - name: fixnum - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.0" flutter: dependency: "direct main" description: flutter source: sdk version: "0.0.0" - flutter_reactive_ble: + flutter_bluetooth_basic: dependency: "direct main" description: - name: flutter_reactive_ble + name: flutter_bluetooth_basic url: "https://pub.dartlang.org" source: hosted - version: "4.0.1" + version: "0.1.7" flutter_redux: dependency: "direct main" description: @@ -212,13 +205,6 @@ packages: description: flutter source: sdk version: "0.0.0" - functional_data: - dependency: transitive - description: - name: functional_data - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.0" gbk_codec: dependency: transitive description: @@ -471,13 +457,6 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "4.2.3" - protobuf: - dependency: transitive - description: - name: protobuf - url: "https://pub.dartlang.org" - source: hosted - version: "2.0.0" provider: dependency: "direct main" description: @@ -499,20 +478,6 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "4.0.0" - reactive_ble_mobile: - dependency: transitive - description: - name: reactive_ble_mobile - url: "https://pub.dartlang.org" - source: hosted - version: "4.0.1" - reactive_ble_platform_interface: - dependency: transitive - description: - name: reactive_ble_platform_interface - url: "https://pub.dartlang.org" - source: hosted - version: "4.0.1" redux: dependency: "direct main" description: @@ -554,7 +519,7 @@ packages: name: rxdart url: "https://pub.dartlang.org" source: hosted - version: "0.27.2" + version: "0.26.0" shared_preferences: dependency: "direct main" description: diff --git a/pubspec.yaml b/pubspec.yaml index bc46b76..a371852 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -23,10 +23,6 @@ environment: dependencies: flutter: sdk: flutter - - - # The following adds the Cupertino Icons font to your application. - # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.3 redux: ^5.0.0 flutter_redux: ^0.8.2 @@ -58,13 +54,10 @@ dependencies: permission_handler: ^8.1.6 flutter_svg: ^0.22.0 grouped_list: ^4.1.0 - #flutter_reactive_ble - flutter_reactive_ble: ^4.0.1 + flutter_bluetooth_basic: ^0.1.7 location_permissions: ^4.0.0 - bluetooth_print: - path: ../bluetooth_print/ esc_pos_utils: ^1.1.0 -# flutter_blue: ^0.8.0 + esc_pos_bluetooth: ^0.4.1 dev_dependencies: flutter_test: sdk: flutter