Skip to content

Commit

Permalink
chore: Update dependencies and remove unused code
Browse files Browse the repository at this point in the history
Update the requirements.txt file to include the latest versions of pyjnius and twisted. Additionally, remove the unused file src/socketio_service.android.py and its corresponding entry in the buildozer.spec file. These changes ensure that the project has up-to-date dependencies and removes unnecessary code.
  • Loading branch information
alevilar committed Sep 5, 2024
1 parent 1bead69 commit 8a26581
Show file tree
Hide file tree
Showing 6 changed files with 193 additions and 95 deletions.
14 changes: 7 additions & 7 deletions buildozer.spec
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ title = Fiscalberry
package.name = fiscalberry

# (str) Package domain (needed for android/ios packaging)
package.domain = fiscalberry.paxapos.com
package.domain = com.paxapos

# (str) Source code where the main.py live
source.dir = src
Expand Down Expand Up @@ -37,7 +37,7 @@ version = 0.1

# (list) Application requirements
# comma separated e.g. requirements = sqlite3,kivy
requirements = python3,kivy,python-escpos,python-socketio,simple-websocket,uuid,appdirs,python-dotenv,platformdirs, pillow, python-barcode, certifi, charset-normalizer, pypng, python-barcode, python-engineio, PyYAML, qrcode, requests, simple-websocket, setuptools, six, typing_extensions, urllib3, websocket-client, wsproto, aiohttp, argparse, uuid, appdirs, python-dotenv, argcomplete
requirements = python3,kivy,python-escpos,python-socketio,simple-websocket,uuid,appdirs,python-dotenv,platformdirs, pillow, python-barcode, certifi, charset-normalizer, pypng, python-barcode, python-engineio, PyYAML, qrcode, requests, simple-websocket, setuptools, six, typing_extensions, urllib3, websocket-client, wsproto, aiohttp, argparse, uuid, appdirs, python-dotenv, argcomplete, pyjnius, twisted

# (str) Custom source folders for requirements
# Sets custom source for any requirements with recipes
Expand All @@ -47,15 +47,15 @@ requirements = python3,kivy,python-escpos,python-socketio,simple-websocket,uuid,
presplash.filename = %(source.dir)s/fiscalberry_app/assets/fiscalberry.png

# (str) Icon of the application
#icon.filename = %(source.dir)s/fiscalberry_app/assets/fiscalberry.png
icon.filename = %(source.dir)s/fiscalberry_app/assets/fiscalberry.png

# (list) Supported orientations
# Valid options are: landscape, portrait, portrait-reverse or landscape-reverse
orientation = portrait

# (list) List of service to declare
#services = NAME:ENTRYPOINT_TO_PY,NAME2:ENTRYPOINT2_TO_PY
services = socketio_service:src/socketio_service.android.py
services = fiscalberryservice:src/fiscalberryservice.android.py:foreground:sticky

#
# OSX Specific
Expand Down Expand Up @@ -97,7 +97,7 @@ android.presplash_color = purple
# (list) Permissions
# (See https://python-for-android.readthedocs.io/en/latest/buildoptions/#build-options-1 for all the supported syntaxes and properties)
#android.permissions = android.permission.INTERNET, (name=android.permission.WRITE_EXTERNAL_STORAGE;maxSdkVersion=18)
android.permissions = android.permission.INTERNET, android.permission.FOREGROUND_SERVICE
android.permissions = INTERNET, FOREGROUND_SERVICE, READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE, ACCESS_NETWORK_STATE

# (list) features (adds uses-feature -tags to manifest)
#android.features = android.hardware.usb.host
Expand Down Expand Up @@ -141,11 +141,11 @@ android.ndk_api = 21
android.accept_sdk_license = True

# (str) Android entry point, default is ok for Kivy-based app
#android.entrypoint = org.kivy.android.PythonActivity
android.entrypoint = org.kivy.android.PythonActivity

# (str) Full name including package path of the Java class that implements Android Activity
# use that parameter together with android.entrypoint to set custom Java class instead of PythonActivity
#android.activity_class_name = org.kivy.android.PythonActivity
android.activity_class_name = org.kivy.android.PythonActivity

# (str) Extra xml to write directly inside the <manifest> element of AndroidManifest.xml
# use that parameter to provide a filename from where to load your custom XML code
Expand Down
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,5 @@ platformdirs==4.2.2
kivy==2.3.0
cython==3.0.11
buildozer==1.5.0
pyjnius==1.6.1
twisted==24.7.0
13 changes: 11 additions & 2 deletions src/fiscalberry_app/fiscalberry.kv
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,23 @@


Label:
id: event_label
id: conectado_label
text: "Conectado!" if app.connected else "Desconectado"
color: (0, 128, 0, 1) if app.connected else (128, 0, 0, 1)
font_size: 48

Button:
id: connect_button
text: "Conectar" if not app.connected else "Desconectar"
on_press: app.start_service() if not app.connected else app.stop_service()
size_hint_y: None
height: 64
background_color: (0, 128, 0, 1) if app.connected else (128, 0, 0, 1)
color: 1, 1, 1, 1


Label:
id: host_label
id: uuid_label
text: app.uuidSmall
font_size: 16
size_hint_y: None
Expand Down
95 changes: 48 additions & 47 deletions src/fiscalberry_app/fiscalberry_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,21 @@
from kivy.uix.image import Image
from kivy.clock import Clock
from kivy.properties import StringProperty, BooleanProperty

from dotenv import load_dotenv
from jnius import autoclass
from common.Configberry import Configberry
from twisted.internet.protocol import Protocol, ClientFactory
from twisted.internet import reactor

# Importo el módulo que se encarga de la comunicación con el servidor
from fiscalberry_sio import FiscalberrySio
from common.discover import send_discover_in_thread
from common.Configberry import Configberry

from common.fiscalberry_logger import getLogger

logger = getLogger()


load_dotenv()

SERVICE_NAME = u'{packagename}.Service{servicename}'.format(
packagename=u'com.paxapos.fiscalberry',
servicename=u'Fiscalberryservice'
)


configberry = Configberry()
Expand Down Expand Up @@ -66,8 +67,6 @@ class FiscalberryApp(App):
disconnected_image = StringProperty(f"{assetpath}/assets/disconnected.png")
connected_image = StringProperty(f"{assetpath}/assets/connected.png")

sioServerUrl = os.environ.get("SIO_SERVER_URL")

connected: bool = BooleanProperty(False)

fiscalberry_sio = None
Expand All @@ -76,44 +75,41 @@ class FiscalberryApp(App):

def __init__(self, **kwargs):
super(FiscalberryApp, self).__init__(**kwargs)

self.sio = self.__socketio_client()


# load APP config
serverUrl = configberry.config.get("SERVIDOR", "sio_host", fallback="")
self.uuid = configberry.config.get("SERVIDOR", "uuid")
self.uuidSmall = self.uuid[:8]

self.sioServerUrl = serverUrl if serverUrl else self.sioServerUrl


def __socketio_client(self):
configberry = Configberry()

logger.info("Preparando Fiscalberry Server")

serverUrl = configberry.config.get("SERVIDOR", "sio_host", fallback="")
uuid = configberry.config.get("SERVIDOR", "uuid")
send_discover_in_thread()
self.fiscalberry_sio = FiscalberrySio(serverUrl, uuid)

sio = self.fiscalberry_sio.sio

@sio.on("connect", namespace='/paxaprinter')
def on_connect():
# change connected property
self.connected = True

@sio.on('disconnect', namespace='/paxaprinter')
def on_disconnect():
self.connected = False


self.fiscalberry_sio.start_only_status_in_thread()

return sio

# Crear la fábrica del cliente y conectar al socket
factory = AppInterConFactory(self)
reactor.connectUNIX("/data/data/com.paxapos.fiscalberry/files/fiscalberry_socket", factory)

def start_service(self, finishing=False):
service = autoclass(SERVICE_NAME)
mActivity = autoclass(u'org.kivy.android.PythonActivity').mActivity
argument = ''
if finishing:
argument = '{"stop_service": 1}'
service.start(mActivity, argument)
if finishing:
self.service = None
else:
self.service = service

self.connected = True

def stop_service(self):
service = autoclass(SERVICE_NAME)
mActivity = autoclass('org.kivy.android.PythonActivity').mActivity
service.stop(mActivity)
self.start_service(finishing=True)
self.connected = False

def start_fiscaberry_service():
service = autoclass('com.paxapos.fiscalberry.ServiceFiscalberryservice')
mActivity = autoclass('org.kivy.android.PythonActivity').mActivity
argument = ''
service.start(mActivity, argument)

def build(self):
self.root = MainLayout()
Expand All @@ -122,6 +118,7 @@ def build(self):

def add_log(self, text):
self.log_widget.add_log(text)


def store_new_host(self, value):
host = value
Expand All @@ -130,6 +127,10 @@ def store_new_host(self, value):
logger.info(f"FiscalberryApp: se guarda nuevo sio_host:: {host}")
configberry.writeKeyForSection("SERVIDOR", "sio_host", host)


def on_resume(self):
if self.service:
self.start_service()

def on_start(self):
"""
Expand All @@ -138,6 +139,7 @@ def on_start(self):
"""

# Iniciar con el ícono rojo por defecto
self.start_service()
logger.info("FiscalberryApp: Iniciando la aplicación")


Expand All @@ -146,8 +148,7 @@ def on_stop(self):
This function is executed when the application is closed.
It is a Kivy function.
"""
if self.fiscalberry_sio:
self.fiscalberry_sio.stop()
logger.info("FiscalberryApp: Deteniendo la aplicación")
self.stop_service()
logger.info("FiscalberryApp: Deteniendo la aplicación")



125 changes: 125 additions & 0 deletions src/fiscalberryservice.android.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
'''
basado en
https://github.com/vesellov/android-twisted-service/blob/master/src/service/main.py
'''
import time
from jnius import autoclass
from android import AndroidService

import time


# importo el modulo que se encarga de la comunicacion con el servidor
from fiscalberry_sio import FiscalberrySio
from common.discover import send_discover_in_thread
from common.Configberry import Configberry


# Obtener el directorio de datos de la aplicación
import android
data_dir = android.get_external_storage_path()

from twisted.internet import reactor
from twisted.internet import protocol
from twisted.web import server, resource

from common.fiscalberry_logger import getLogger
logger = getLogger()

from twisted.internet.defer import setDebugging
setDebugging(True)

from twisted.python.log import startLogging
startLogging(sys.stdout)



def set_auto_restart_service(restart=True):
logger.info('set_auto_restart_service restart=%r', restart)
from jnius import autoclass
Service = autoclass('org.kivy.android.PythonService').mService
Service.setAutoRestartService(restart)


def set_foreground():
logger.info('set_foreground')
from jnius import autoclass
channel_id = 'com.paxapos.fiscalberry.Fiscalberryserver'
Context = autoclass(u'android.content.Context')
Intent = autoclass(u'android.content.Intent')
PendingIntent = autoclass(u'android.app.PendingIntent')
AndroidString = autoclass(u'java.lang.String')
NotificationBuilder = autoclass(u'android.app.Notification$Builder')
NotificationManager = autoclass(u'android.app.NotificationManager')
NotificationChannel = autoclass(u'android.app.NotificationChannel')
notification_channel = NotificationChannel(
channel_id, AndroidString('TwistedSample Channel'.encode('utf-8')), NotificationManager.IMPORTANCE_HIGH)
Notification = autoclass(u'android.app.Notification')
service = autoclass('org.kivy.android.PythonService').mService
PythonActivity = autoclass(u'org.kivy.android.PythonActivity')
notification_service = service.getSystemService(
Context.NOTIFICATION_SERVICE)
notification_service.createNotificationChannel(notification_channel)
app_context = service.getApplication().getApplicationContext()
notification_builder = NotificationBuilder(app_context, channel_id)
title = AndroidString("Fiscalberry".encode('utf-8'))
message = AndroidString("Aplicación corriendo en background".encode('utf-8'))
app_class = service.getApplication().getClass()
notification_intent = Intent(app_context, PythonActivity)
notification_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK)
notification_intent.setAction(Intent.ACTION_MAIN)
notification_intent.addCategory(Intent.CATEGORY_LAUNCHER)
intent = PendingIntent.getActivity(service, 0, notification_intent, 0)
notification_builder.setContentTitle(title)
notification_builder.setContentText(message)
notification_builder.setContentIntent(intent)
Drawable = autoclass(u"{}.R$drawable".format(service.getPackageName()))
icon = getattr(Drawable, 'icon')
notification_builder.setSmallIcon(icon)
notification_builder.setAutoCancel(True)
new_notification = notification_builder.getNotification()
service.startForeground(1, new_notification)
logger.info('set_foreground DONE : %r' % service)

class Fiscalberryservice():

def __init__(self):
self.service = AndroidService('Fiscal Service', 'Running')
self.service.start_in_thread('Fiscal Service Running')
self.run()

def start(self):
configberry = Configberry()
serverUrl = configberry.config.get("SERVIDOR", "sio_host", fallback="")
uuid = configberry.config.get("SERVIDOR", "uuid")
send_discover_in_thread()
sio = FiscalberrySio(serverUrl, uuid)
sio.start_print_server()

def stop(self):
self.service.stop()

if __name__ == '__main__':
fbs = FiscalberryService()

argument = os.environ.get('PYTHON_SERVICE_ARGUMENT', 'null')
argument = json.loads(argument) if argument else None
argument = {} if argument is None else argument
logger.info('argument=%r', argument)
if argument.get('stop_service'):
logger.info('service to be stopped')
fbs.stop()
return
try:
set_foreground()
set_auto_restart_service()
logger.info('starting fiscalberry sockeit io client')
fbs.start() # aca bloquea con sio.wait()
logger.info('finalizo socket io client')
set_auto_restart_service(False)
except Exception:
logger.exception('Exception in main()')
# avoid auto-restart loop
set_auto_restart_service(False)
Loading

0 comments on commit 8a26581

Please sign in to comment.