Skip to content

Commit

Permalink
- adds raw ColorTrack data
Browse files Browse the repository at this point in the history
- adds option to manually add a roast to an open schedule item
  • Loading branch information
MAKOMO committed Oct 25, 2024
1 parent 8a518b2 commit 328ab56
Show file tree
Hide file tree
Showing 72 changed files with 81,760 additions and 79,999 deletions.
6 changes: 3 additions & 3 deletions src/artisanlib/ble_port.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ def scan_and_connect(self,
blacklist:Set[str], # list of client addresses to ignore as they don't offer the required service
case_sensitive:bool=True,
disconnected_callback:Optional[Callable[[BleakClient], None]] = None,
scan_timeout:float=5,
scan_timeout:float=10,
connect_timeout:float=3) -> Tuple[Optional[BleakClient], Optional[str]]:
if hasattr(self, '_asyncLoopThread') and self._asyncLoopThread is None:
self._asyncLoopThread = AsyncLoopThread()
Expand Down Expand Up @@ -274,7 +274,7 @@ def connected(self) -> Optional[str]:


# connect and re-connect while self._running to BLE
async def _connect(self, case_sensitive:bool=True, scan_timeout:float=5, connect_timeout:float=3) -> None:
async def _connect(self, case_sensitive:bool=True, scan_timeout:float=10, connect_timeout:float=3) -> None:
blacklist:Set[str] = set()
while self._running:
# scan and connect
Expand Down Expand Up @@ -377,7 +377,7 @@ async def _connect_and_keep_alive(self,case_sensitive:bool,scan_timeout:float, c
self._keep_alive())


def start(self, case_sensitive:bool=True, scan_timeout:float=5, connect_timeout:float=3) -> None:
def start(self, case_sensitive:bool=True, scan_timeout:float=10, connect_timeout:float=3) -> None:
_log.debug('start')
if self._running:
_log.error('BLE client already running')
Expand Down
2 changes: 1 addition & 1 deletion src/artisanlib/canvas.py
Original file line number Diff line number Diff line change
Expand Up @@ -1466,7 +1466,7 @@ def __init__(self, parent:QWidget, dpi:int, locale:str, aw:'ApplicationWindow')
# profile UUID
self.roastUUID:Optional[str] = None
self.scheduleID:Optional[str] = None
self.scheduleDate:Optional[str] = None
self.scheduleDate:Optional[str] = None # not stored on server and thus might be None while scheduleID is not None (in case scheduleID got set on server side)

#PLUS
# the default store selected by the user (save in the app settings)
Expand Down
23 changes: 17 additions & 6 deletions src/artisanlib/colortrack.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
except ImportError:
from PyQt5.QtCore import QRegularExpression # type: ignore # @UnusedImport @Reimport @UnresolvedImport

from typing import Final, Optional, Callable, TYPE_CHECKING
from typing import Final, Optional, Callable, Tuple, TYPE_CHECKING

if TYPE_CHECKING:
from PyQt6.QtCore import QRegularExpressionMatch # pylint: disable=unused-import
Expand Down Expand Up @@ -142,8 +142,9 @@ def __init__(self, connected_handler:Optional[Callable[[], None]] = None,

# weights for averaging (length 40) # ColorTrack sends about 65 laser readings per second
self._weights:Final[npt.NDArray[np.float64]] = np.array(range(1, 40))
# received but not yet consumed readings
# received but not yet consumed readings (mapped)
self._received_readings:npt.NDArray[np.float64] = np.array([])
self._received_raw_readings:npt.NDArray[np.float64] = np.array([])


def map_reading(self, r:int) -> float:
Expand All @@ -156,22 +157,31 @@ def register_reading(self, value:float) -> None:
if self._logging:
_log.info('register_reading: %s',value)

def getColor(self) -> float:
def register_raw_reading(self, value:float) -> None:
self._received_raw_readings = np.append(self._received_raw_readings, value)

# second result is the raw average
def getColor(self) -> Tuple[float, float]:
read_res = self.read(self.COLORTRACK_READ_NOTIFY_LASER_UUID)
_log.info('PRINT getLaser: %s',read_res)
try:
number_of_readings = len(self._received_readings)
number_of_raw_readings = len(self._received_raw_readings)
if number_of_readings == 1:
return float(self._received_readings[0])
return float(self._received_readings[0]), (float(self._received_raw_readings[0]) if number_of_raw_readings==1 else -1)
if number_of_readings > 1:
# consume and average the readings
l = min(len(self._weights), number_of_readings)
res:float = float(np.average(self._received_readings[-l:], weights=self._weights[-l:]))
self._received_readings = np.array([])
return res
# raw
l_raw = min(len(self._weights), number_of_raw_readings)
res_raw:float = float(np.average(self._received_raw_readings[-l_raw:], weights=self._weights[-l_raw:]))
self._received_raw_readings = np.array([])
return res, res_raw
except Exception as e: # pylint: disable=broad-except
_log.exception(e)
return -1
return -1, -1

# every second reading is the sync character 36
# returns readings as bytes extracted from the given payload. If the payload is not valid the result is empty.
Expand All @@ -189,6 +199,7 @@ def validate_data(payload:bytearray) -> bytearray:
def notify_laser_callback(self, _sender:'BleakGATTCharacteristic', payload:bytearray) -> None:
for r in self.validate_data(payload):
self.register_reading(self.map_reading(r))
self.register_raw_reading(r)

@staticmethod
def notify_temp_hum_callback(_sender:'BleakGATTCharacteristic', payload:bytearray) -> None:
Expand Down
6 changes: 4 additions & 2 deletions src/artisanlib/comm.py
Original file line number Diff line number Diff line change
Expand Up @@ -1457,8 +1457,10 @@ def ColorTrackBT(self) -> Tuple[float,float,float]:
if self.colorTrackBT is not None:
self.colorTrackBT.start()
tx = self.aw.qmc.timeclock.elapsedMilli()
color = (-1 if self.colorTrackBT is None else self.colorTrackBT.getColor())
return tx,color,color
ct_color, ct_raw_color = self.colorTrackBT.getColor()
color = (-1 if self.colorTrackBT is None else ct_color)
raw_color = (-1 if self.colorTrackBT is None else ct_raw_color)
return tx,color,raw_color

def ARDUINOTC4(self) -> Tuple[float,float,float]:
self.aw.qmc.extraArduinoTX = self.aw.qmc.timeclock.elapsedMilli()
Expand Down
3 changes: 2 additions & 1 deletion src/artisanlib/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -1493,7 +1493,7 @@ class ApplicationWindow(QMainWindow): # pyright: ignore [reportGeneralTypeIssue
'sliderLCD4', 'sliderGrpBox1', 'sliderGrpBox2', 'sliderGrpBox3', 'sliderGrpBox4', 'sliderSV', 'sliderLCDSV', 'sliderGrpBoxSV', 'leftlayout',
'sliderFrame', 'lcdFrame', 'midlayout', 'editgraphdialog', 'html_loader', 'QtWebEngineSupport', 'artisanviewerFirstStart',
'buttonpalette', 'extraeventbuttontextcolor', 'extraeventsactions', 'extraeventsdescriptions', 'extraeventstypes', 'extraeventsvalues',
'extraeventsvisibility', 'fileSaveAction', 'fileSaveAsAction', 'keyboardButtonStyles', 'language_menu_actions', 'loadThemeAction', 'main_button_min_width_str',
'extraeventsvisibility', 'fileSaveAsAction', 'keyboardButtonStyles', 'language_menu_actions', 'loadThemeAction', 'main_button_min_width_str',
'minieventleft', 'minieventright', 'nLCDS', 'notificationManager', 'notificationsflag', 'ntb', 'pdf_page_layout', 'pdf_rendering', 'productionPDFAction',
'rankingPDFAction', 'roastReportMenu', 'roastReportPDFAction', 'saveAsThemeAction', 'sliderGrp12', 'sliderGrp34', 'sliderGrpBox1x', 'sliderGrpBox2x', 'sliderGrpBox3x', 'sliderGrpBox4x',
'small_button_min_width_str', 'standard_button_min_width_px', 'tiny_button_min_width_str', 'recording_version', 'recording_revision', 'recording_build',
Expand Down Expand Up @@ -19633,6 +19633,7 @@ def stopActivities(self) -> None:

if self.scheduleFlag and self.schedule_window:
tmp_Schedule = self.scheduleFlag # we keep the state to properly store it in the settings
self.scheduler_auto_open = False
self.schedule_window.close()
self.scheduleFlag = tmp_Schedule

Expand Down
4 changes: 2 additions & 2 deletions src/plus/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ def connect(clear_on_failure: bool =False, interactive: bool = True) -> None:
if success:
config.connected = success
config.app_window.sendmessageSignal.emit(
f'{config.app_window.plus_account} {QApplication.translate("Plus", "authentified")}',
f'{config.app_window.plus_account} {QApplication.translate('Plus', 'authentified')}',
True,
None,
) # @UndefinedVariable
Expand Down Expand Up @@ -400,7 +400,7 @@ def reconnected() -> None:
queue.start() # restart the outbox queue


# if on and synced, computes the sync record hash, updates the
# if plus is ON and synced, computes the sync record hash, updates the
# sync record cache and returns the sync record hash
# otherwise return None
# this function is called by filesave() and returns the sync_record hash
Expand Down
16 changes: 9 additions & 7 deletions src/plus/roast.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,8 @@ def getTemplate(bp: 'ProfileData', background:bool=False) -> Dict[str, Any]: #f
_log.exception(e)

util.add2dict(bp, config.uuid_tag, d, 'id') # roast UUID
util.add2dict(bp, config.schedule_uuid_tag, d, 's_item_id') # ScheduleItem UUID
util.add2dict(bp, config.schedule_date_tag, d, 's_item_date') # ScheduleItem date
util.add2dict(bp, config.schedule_uuid_tag, d, 's_item_id', if_non_empty=False) # ScheduleItem UUID (add also also if None!)
util.add2dict(bp, config.schedule_date_tag, d, 's_item_date', if_non_empty=False) # ScheduleItem date (added to speed up search on server side; also if None)

try:
util.addNum2dict(bp, 'moisture_roasted', d, 'moisture', 0, 100, 1)
Expand Down Expand Up @@ -479,13 +479,15 @@ def getRoast() -> Dict[str, Any]: #for Python >= 3.9 can replace 'Dict' with th
'cupping_notes',
]

# those will always be send by Artisan also if None or 0:
sync_record_non_supressed_attributes: List[str] = [ #for Python >= 3.9 can replace 'List' with the generic type hint 'list'
'roast_id',
'location',
'coffee',
'blend',
'amount',
'end_weight',
'location', # default None
'coffee', # default None
'blend', # default None
'amount', # default 0
'end_weight', # default 0
's_item_id', # default None
]

# all roast record attributes that participate in the sync process
Expand Down
Loading

0 comments on commit 328ab56

Please sign in to comment.