Build Your Own Scoreboard
Would you like to react to this message? Create an account in a few clicks or log in to continue.

Problem with Play Cricket Scorer app and Overs Bowled not always updating

5 posters

Page 1 of 2 1, 2  Next

Go down

Problem with Play Cricket Scorer app and Overs Bowled not always updating Empty Problem with Play Cricket Scorer app and Overs Bowled not always updating

Post by PatrickT1 Tue Oct 10, 2023 12:43 pm

Firstly, thanks so much for all the info on this site. I built our scoreboard last winter (2022-23) and we have been using it all season with much success. I will be putting up a write up in the relevant section on the forum at some point.

I have noticed over the season and in testing that when using the bluetooth connection from PCS app the overs bowled does not always stay up to date. Sometimes it can be as much as 3 overs before getting an update.

In testing I can see that the OVB field from the app is intermittently not coming through from PCS.

Is anyone else seeing this issue?

I am wondering if it's a problem with the app, or a problem with not processing the data quick enough on the Pi (I don't know if the serial data gets queued by the Pi or if it could get missed if the loop isn't quick enough), or maybe something else I haven't thought of.

If you've had any experience of this I'd be grateful to hear if you've found a solution.

PatrickT1

Posts : 30
Join date : 2023-06-23
Location : Collingbourne CC

Back to top Go down

Problem with Play Cricket Scorer app and Overs Bowled not always updating Empty Re: Problem with Play Cricket Scorer app and Overs Bowled not always updating

Post by Tony.Rogers Sat Oct 14, 2023 10:01 pm

I was testing my board this evening (simple 9 digit board) and I seem to have a similar problem, except mine is the Wickets that doesn't always get updated.
In case it's relevant, my strings are:
Str1-Total / Wkts / Overs
Str2-Target

Tony.Rogers

Posts : 31
Join date : 2017-11-30

Back to top Go down

Problem with Play Cricket Scorer app and Overs Bowled not always updating Empty Re: Problem with Play Cricket Scorer app and Overs Bowled not always updating

Post by wcc-dave Fri May 03, 2024 8:04 pm

Hi, did you get to the bottom of this? I've just built a board for my CC and I'm seeing exactly the issue you describe using Play Cricket and the delay to the overs. Using the Web page method of scoring everything is perfect so I don't think it's the electronics.

I'm going to run the diag scripts to see what's being sent to the arduino but any thoughts would be greatly appreciated.

wcc-dave

Posts : 9
Join date : 2023-06-23

Back to top Go down

Problem with Play Cricket Scorer app and Overs Bowled not always updating Empty Re: Problem with Play Cricket Scorer app and Overs Bowled not always updating

Post by PatrickT1 Fri May 03, 2024 8:14 pm

No - I used a bluetooth monitor on my phone to capture all the data coming from the scoreboard showing the missing overs data, sent it to the Play Cricket support team, and they basically told me it couldn't happen, and must be the scoreboard bluetooth at fault.

I've been looking for a suitable bluetooth dongle for my RPi 3B (in case it's the built in bluetooth at fault) but haven't had the time to look at it further.

PatrickT1

Posts : 30
Join date : 2023-06-23
Location : Collingbourne CC

Back to top Go down

Problem with Play Cricket Scorer app and Overs Bowled not always updating Empty Re: Problem with Play Cricket Scorer app and Overs Bowled not always updating

Post by wcc-dave Sat May 04, 2024 7:43 am

Lol, a standard IT response. Blame the unsupported hardware. I've got an old Pi and Arduino kicking about at home. I can try a different Bluetooth dingle too.

wcc-dave

Posts : 9
Join date : 2023-06-23

Back to top Go down

Problem with Play Cricket Scorer app and Overs Bowled not always updating Empty Re: Problem with Play Cricket Scorer app and Overs Bowled not always updating

Post by wcc-dave Sat May 04, 2024 8:48 am

Have your tried the Play Cricket Pro app on PC? Is that the same?

wcc-dave

Posts : 9
Join date : 2023-06-23

Back to top Go down

Problem with Play Cricket Scorer app and Overs Bowled not always updating Empty Re: Problem with Play Cricket Scorer app and Overs Bowled not always updating

Post by PatrickT1 Sat May 04, 2024 9:37 am

The scorer app on PC is different and I think connects to the scoreboard in a different way - I haven't used it, so not totally sure.

It might be helpful if you report it to the people at play cricket - at least then there's more than just one report of the issue...

PatrickT1

Posts : 30
Join date : 2023-06-23
Location : Collingbourne CC

Back to top Go down

Problem with Play Cricket Scorer app and Overs Bowled not always updating Empty Re: Problem with Play Cricket Scorer app and Overs Bowled not always updating

Post by targett2023 Sun May 05, 2024 5:46 pm

The issue here, I believe, and I am afraid to say, because there is no robust quick fix, is that some of the the bluetooth packets sent from PCS are been missed. The PCS link code you are using is flawed. Whilst it processes each packet, it is essentially blocking the main thread (the one with the dbus event loop) and messages are missed. The issue is hardware dependent; you may or may not see it depending on which fields you access, the order you do so, and the combination of hardware you are using (pi/phone). The only robust solution is to write some multi-threaded code using a classic producer-consumer pattern. You have one thread whose sole responsibility is to look out for bluetooth packets; when it receives them, it does zero-processing other than adding the bytes to a queue. Then you have another thread which monitors the queue, pops the messages off, and does the processing. PCS could solve this problem by sending the data all in one go, rather than broadcasting lots of single packets of data a quarter of a second (or whatever) apart. Stupid way of doing it if you ask me.

targett2023

Posts : 17
Join date : 2023-06-23

Back to top Go down

Problem with Play Cricket Scorer app and Overs Bowled not always updating Empty Re: Problem with Play Cricket Scorer app and Overs Bowled not always updating

Post by targett2023 Sun May 05, 2024 9:14 pm

The other thing you could try which could be simpler is to split the program into two and communicate between the two with a socket. So, in one program you just have the bluetooth code (you'll have to strip the script down), and every time the characteristic is written send the bytes down a socket to another program which receives the socket messages and does the rest of the processing.

targett2023

Posts : 17
Join date : 2023-06-23

Back to top Go down

Problem with Play Cricket Scorer app and Overs Bowled not always updating Empty Re: Problem with Play Cricket Scorer app and Overs Bowled not always updating

Post by PatrickT1 Sun May 05, 2024 9:20 pm

My testing did lead me to think it was something to do with the timing of the messages from PCS.

My programming skills are not up to being able to make the changes you suggest, but maybe someone on here can look at it.

Strange that most of the time it works fine, but then goes through a spell of missing just that one piece of data (it's always the overs bowled for me).

Wonder if a faster processor on a later RPi would make a difference?

PatrickT1

Posts : 30
Join date : 2023-06-23
Location : Collingbourne CC

Back to top Go down

Problem with Play Cricket Scorer app and Overs Bowled not always updating Empty Re: Problem with Play Cricket Scorer app and Overs Bowled not always updating

Post by targett2023 Mon May 06, 2024 8:45 am

I use a pi4. I had a system up and running, that I thought was watertight, and then someone tried it with a pixel 6 and it returned! The pi alone does not cause the problem. It is the combination of pi/phone.
I can probably send you a toy setup in python. You will have to do some coding though to extract your hardware specific code from the existing Bluetooth script. It won't be too hard. I use a completely different hardware set-up and program in C.

targett2023

Posts : 17
Join date : 2023-06-23

Back to top Go down

Problem with Play Cricket Scorer app and Overs Bowled not always updating Empty Re: Problem with Play Cricket Scorer app and Overs Bowled not always updating

Post by PatrickT1 Mon May 06, 2024 8:56 am

I had a play with chatGPT and the uart_peripheral.py script last night with a view to converting it to multithreading with a data queue - it came up with some promising changes to try.

I need to have a play and see if I can get it working. Will report back if I manage to make progress.

PatrickT1

Posts : 30
Join date : 2023-06-23
Location : Collingbourne CC

Back to top Go down

Problem with Play Cricket Scorer app and Overs Bowled not always updating Empty Re: Problem with Play Cricket Scorer app and Overs Bowled not always updating

Post by PatrickT1 Mon May 06, 2024 9:22 am

Just thinking back to the testing I did before to send the info to the PCS support team - I was able to replicate this problem without the Pi (and therefore the uart_peripheral.py script) in the mix.

I used an Amazon Fire tablet running PCS app, and cloned the scoreboard device using nrfConnect app on my phone (Galaxy S23).

The OVB field would still be missing occasionally, although all the other fields were sent reliably.

As I said to the support team, this rules out the scoreboard hardware and software, and points the finger at their app, but they were having none of it.

Even multiple presses of the Refresh Scoreboard button in the PCS app would not send the OVB field.

Any thoughts?


PatrickT1

Posts : 30
Join date : 2023-06-23
Location : Collingbourne CC

Back to top Go down

Problem with Play Cricket Scorer app and Overs Bowled not always updating Empty Re: Problem with Play Cricket Scorer app and Overs Bowled not always updating

Post by targett2023 Mon May 06, 2024 9:24 am

Actually, it was much simpler than I thought. Personally, I wouldn't use those scripts. I think they're over a decade old. Tbf, I think bluez themselves still use them so probably ok.

i) We'll use a third party library called bluez-peripheral. Install it using pip and then you're good to go.
ii) So, in one file, "toy_bluetooth_server.py", copy and paste the code below. You can see how much simpler this library makes things. It implements an entire bluetooth server in 58 lines!

Code:

from bluez_peripheral.gatt.service import Service
from bluez_peripheral.gatt.characteristic import characteristic, CharacteristicFlags as CharFlags
from bluez_peripheral.util import *
from bluez_peripheral.advert import Advertisement
from bluez_peripheral.agent import NoIoAgent
import asyncio
import threading
import socket
from queue import Queue

host = socket.gethostname()
port = 5000

queue = Queue()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))

def clientSocket():
    while True:
        try:
            if not queue.empty():
                s.send(queue.get())
        except KeyboardInterrupt:
            break
    s.close()

class ToyService(Service):
    def __init__(self):
        super().__init__("5a0d6a15-b664-4304-8530-3a0ec53e5bc1", True)

    @characteristic("df531f62-fc0b-40ce-81b2-32a6262ea440", CharFlags.WRITE).setter
    def toyWriteCharacteristic(self, value, options):
        queue.put(value)

async def main():
    bus = await get_message_bus()

    service = ToyService()
    await service.register(bus)

    agent = NoIoAgent()
    await agent.register(bus)

    adapter = await Adapter.get_first(bus)

    advert = Advertisement("My Scoreboard", ["5a0d6a15-b664-4304-8530-3a0ec53e5bc1"], 0x0140, 0)
    await advert.register(bus, adapter)

    socketThread = threading.Thread(target=clientSocket)
    socketThread.start()

    while True:
        await asyncio.sleep(5)

    await bus.wait_for_disconnect()

if __name__ == "__main__":
    asyncio.run(main())

iii) In another file, "toy_scoreboard.py", copy and paste the following 20 lines:

Code:

import socket

def server_program():
    host = socket.gethostname()
    port = 5000
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
        server_socket.bind((host, port))
        server_socket.listen(2)
        conn, address = server_socket.accept()
        print("Connection from: " + str(address))
        while True:
            data = conn.recv(1024).decode()
            if len(data) <= 0:
                break
            print("From connected user: " + str(data))
            # Update your scoreboard here. Ideally, you should probbably use a queue and multithread,
            # but I have a feeling the socket is already queuing messages for you.

if __name__ == '__main__':
    server_program()

iv) Open one terminal and run "toy_scoreboard.py". You must run this first.
v) Open another terminal and run "toy_bluetooth_server.py"
vi) Now connect from PCS to "My Scoreboard", you'll see the packets being dumped on the terminal running "toy_scoreboard.py".
vii) There you go: zero to hero in less than 100 lines of code.
viii) You'll have to extract all the hardware specific stuff from the old script and place into the highlighted position (see comment) in "toy_scoreboard.py". That shouldn't be difficult to do.

I actually did both solutions in "toy_bluetooth_server.py" i.e. multi-threaded the packets into a queue and sent them down a socket to another process which just deals with the hardware. I think this separation of responsibilities is sensible. I'll be on hand to help if you have any issues. Let me know how it turns out.

targett2023

Posts : 17
Join date : 2023-06-23

Back to top Go down

Problem with Play Cricket Scorer app and Overs Bowled not always updating Empty Re: Problem with Play Cricket Scorer app and Overs Bowled not always updating

Post by Tony.Rogers Mon May 06, 2024 9:31 am

PatrickT1 wrote:I had a play with chatGPT and the uart_peripheral.py script last night with a view to converting it to multithreading with a data queue - it came up with some promising changes to try.

I need to have a play and see if I can get it working. Will report back if I manage to make progress.

With some coding help I now have this which runs in the way you describe, it also outputs pretty much all the PCS data to a new json file & the plan is to create a new spectator board with lots of data (that's still work in progress). I already have a PCS json stectator board that just displays the basics (total, wkts, overs, Target, Runs Req)

PS my py script adds one to the FTS to get a Target variable & sends that to the board. Now I can use TGT or RRQ.

I can't get the OVB or OVR to save to the json with decimals but I'm still playing with that.

Hopefully might save you some work.

Code:

# version PCSenhanced 0.001. Variables not defined error when running py script
# version PCSenhanced 0.002 Fixed error in 0.001. Outputs large data string to json but some data is duplicated
# version PCSenhanced 0.003 Comment out new variables & then reintroduce 1 at a time
# version PCSenhanced 0.004 Started reintroducing variables - added B1S & B2S BROKEN
# version PCSenhanced 0.005 B1S & B2S didn't work but 0.005 works with pre-existing BatA & BatB WORKING
# version PCSenhanced 0.006 added Batsman Balls Faced, WORKING
# version PCSenhanced 0.007 added pcsCOV. WORKING
# version PCSenhanced 0.008 added both batsmans names & both Bowlers names & scores. WORKING
# version PCSenhanced 0.009 added everything else all in one go. optimistic but let's see !
# version PCSenhanced 0.011 all working EXCEPT Overs Bowled & Remaning don't have the decimal. Need 'overs' for board & 'pcsOVB' for spectator
# version PCSenhanced 0.012 changed data string order trying to get the json output file in order. Needs Python 3.7 which is now used

import serial, time
import sys
import dbus, dbus.mainloop.glib
import json

from gi.repository import GLib
from example_advertisement import Advertisement
from example_advertisement import register_ad_cb, register_ad_error_cb
from example_gatt_server import Service, Characteristic
from example_gatt_server import register_app_cb, register_app_error_cb

BLUEZ_SERVICE_NAME =          'org.bluez'
DBUS_OM_IFACE =                'org.freedesktop.DBus.ObjectManager'
LE_ADVERTISING_MANAGER_IFACE = 'org.bluez.LEAdvertisingManager1'
GATT_MANAGER_IFACE =          'org.bluez.GattManager1'
GATT_CHRC_IFACE =              'org.bluez.GattCharacteristic1'
UART_SERVICE_UUID =            '5a0d6a15-b664-4304-8530-3a0ec53e5bc1'
UART_RX_CHARACTERISTIC_UUID =  'df531f62-fc0b-40ce-81b2-32a6262ea440'
LOCAL_NAME =                  'FoSCC-Scoreboard-TGT'

mainloop = None

# Set all the Scoreboard variables to starting positions

Wickets = "0"
Overs = "-0"
BatTotal = "--0"
BatAscore = "--0"
BatBscore = "--0"
Target = "---"
pcsCOV = "-"
#pcsOVB = "-"
#pcsOVR = "-"
pcsRRQ = "-"
pcsRRR = "-"
pcsBTN = "-"
pcsFTN = "-"
pcsFTS = "-"
pcsBAN = "-"
#pcsB1S = "0"
pcsB1B = "-"
pcsB1K = "-"
pcsBBN = "-"
#pcsB2S = "0"
pcsB2B = "-"
pcsB2K = "-"
pcsF1N = "-"
pcsF1S = "-"
pcsF2N = "-"
pcsF2S = "-"
pcsLWK = "-"
pcsDLT = "-"
pcsDLP = "-"

def update_scoreboard():
    Scoreboard = "4," + BatTotal + "," + Wickets + "," + Overs + "," + Target + "#"
    print(Scoreboard)
    with serial.Serial("/dev/ttyACM0", 57600, timeout=1) as arduino:
        # time.sleep(0.1) #wait for serial to open
        if arduino.isOpen():
            print("{} connected!".format(arduino.port))
            arduino.write(Scoreboard.encode())
            print("Data Sent: " + Scoreboard)
            arduino.close
    score_data = {
        "total": BatTotal,
        "wickets": Wickets,
        "overs": Overs,
#        "OversBowled": pcsOVB,
#        "OversRem": pcsOVR,
        "target": Target,
        "BatTeamName": pcsBTN,
        "RunsReq": pcsRRQ,
        "ReqRunRate": pcsRRR,
        "DLSTarget": pcsDLT,
        "DLSPar": pcsDLP,
        "Bat1Name": pcsBAN,
        "BatAscore": BatAscore,
#        "Bat1Score": pcsB1S,
        "BatABallsFaced": pcsB1B,
        "Bat1onStrike": pcsB1K,
        "Bat2Name": pcsBBN,
        "BatBscore": BatBscore,
#        "Bat2Score": pcsB2S,
        "BatBBallsFaced": pcsB2B,
        "Bat2onStrike": pcsB2K,
        "LastWicket": pcsLWK,
        "FieldTeamName": pcsFTN,
        "FieldTeamScore": pcsFTS,
        "CurrBowlName": pcsF1N,
        "CurrBowlFigs": pcsF1S,
        "CurrentOver": pcsCOV,
        "PrevBowlName": pcsF2N,
        "PrevBowlFigs": pcsF2S,
    }
    print("score_data =", score_data)
    with open('/var/www/html/scorePCS.json', 'w') as jsonf:
        json.dump(score_data, jsonf)


Scoreboard = "4," + BatTotal + "," + Wickets + "," + Overs + "," + Target + "#"

# Open the serial port and set the Scoreboard to starting positions

#with serial.Serial("/dev/ttyACM0", 57600, timeout=1) as arduino:
    # time.sleep(0.1) #wait for serial to open
#    if arduino.isOpen():
#            print("{} connected!".format(arduino.port))
#            arduino.write(Scoreboard.encode())
#            print("Data Sent: " + Scoreboard)
#            arduino.close
update_scoreboard()

class RxCharacteristic(Characteristic):
    def __init__(self, bus, index, service):
        Characteristic.__init__(self, bus, index, UART_RX_CHARACTERISTIC_UUID,
                                ['write'], service)

    def WriteValue(self, value, options):
        global Wickets
        global Overs
        global BatTotal
        global BatAscore
        global BatBscore
        global Target
        global Scoreboard
        # New code for enhanced Spectator board START
        global pcsCOV #Current Over
#        global pcsOVB #Need this for spectator board in addition to 'overs' as overs is truncated but we want the scoreboard to display the decimal point
#        global pcsOVR #Overs Remaining
        global pcsRRQ #Runs Required
        global pcsRRR #Run Rate Required
        global pcsBTN #Batting Team Name
        global pcsBTS #not needed as already in code
        global pcsFTN #Fielding Team Name
        global pcsFTS #Fielding Team Score (1 is added to this to generate 'target' as target is not a PCS variable
        global pcsBAN #Batsman 1 name
        #global pcsB1S #Batsman 1 score not needed as already in code
        global pcsB1B #Batsman 1 Balls Faced
        global pcsB1K #Batsman 1 on strike? (Yes - 1, No - 0)
        global pcsBBN #Batsman 2 name
        #global pcsB2S #Batsman 2 score not needed as already in code
        global pcsB2B #Batsman 2 Balls Faced
        global pcsB2K #Batsman 2 on strike? (Yes - 1, No - 0)
        global pcsF1N #Current Bowler Name
        global pcsF1S #Current Bowler Figures
        global pcsF2N #Previous Bowler Name
        global pcsF2S #Previous Bowler Figures
        global pcsLWK #Last Wicket
        global pcsDLT #Duckworth Lewis target
        global pcsDLP #Duckworth Lewis Par at end of current over
        # New code for enhanced Spectator board END
        try:
            WriteReturn = '{}'.format(bytearray(value).decode())
            ScoreType = WriteReturn[0:3]
            ScoreData = WriteReturn[3:]
       #if the bluetooth data is of type OVB, B1S, B2S, BTS, FTS then we need to update the scoreboard.  Other messages can be ignore.
            UpdateScoreboard = True
            if ScoreType == "OVB":                                          # Let's deal with Overs Bowled!
                if ScoreData.find(".") == -1:                              # If there's no dot because it's the end of the over, just format the number and use it
                    Overs = ScoreData.rjust(2,"-")
                else:
                    Overs = ScoreData.split(".",1)[0].rjust(2,"-")          # If there's a dot, take whatever's before it.  Cheap way of rounding down without using a float
            elif ScoreType == "B1S":                                        # Batsman 1 score formatted with leading dashes for blanks
                BatAscore = ScoreData.rjust(3,"-")
            elif ScoreType == "B2S":                                        # Batsman 2 score formatted with leading dashes for blanks
                BatBscore = ScoreData.rjust(3,"-")
            elif ScoreType == "BTS":                                        # Batting Team Score
                TempSplit = ScoreData.split(" &",1)[0]                      # Current Inning Score only (split everything before the ampersand)
                BatTotal = TempSplit.split("/",1)[0].rjust(3,"-")          # Everything before the dash is the score, with leading dashes for blanks
                Wickets = TempSplit.split("/",1)[1].replace("10","-")      # Everything after the dash is the wickets, and if it's all out (10) then make it blank because we only have 1 digit
            elif ScoreType == "FTS":
                TempSplit = ScoreData.split(" &",1)[0]                      # Current Inning Score only
                Target = TempSplit.split("/",1)[0]                  # Everything before the dash is the score, with leading dashes for blanks
                Target = str(int(Target) + 1).rjust(3,"-")
               
            # New code for enhanced Spectator board START
            elif ScoreType == "COV":                                        # Current Over Details
                pcsCOV = ScoreData
#            elif ScoreType == "OVB":                                        # Overs Bowled for spectator board as overs is truncated & we want the full number
#                pcsOVB = ScoreData
#            elif ScoreType == "OVR":                                        # Overs Remaining for spectator board as overs is truncated & we want the full number
#                pcsOVR = ScoreData
            elif ScoreType == "RRQ":                                        # Runs Required for spectator board
                pcsRRQ = ScoreData
            elif ScoreType == "RRR":                                        # Run Rate Required for spectator board
                pcsRRR = ScoreData 
            elif ScoreType == "BTN":                                        # Batting Team Name
                pcsBTN = ScoreData
                pcsBTN = pcsBTN[:10]
            elif ScoreType == "FTN":                                        # Fielding Team Name
                pcsFTN = ScoreData
                pcsFTN = pcsFTN[:10]
            elif ScoreType == "FTS":                                        # Fielding Team Score (1 is added to this to generate 'target' as target is not a PCS variable
                pcsFTN = ScoreData
                pcsFTN = pcsFTN[:10]
            elif ScoreType == "B1N":                                        # Batsman 1 Name
                pcsBAN = ScoreData
                pcsBAN = pcsBAN[:10]
            elif ScoreType == "B1S":                                        # Batsman 1 score formatted with leading dashes for blanks
                Bat1Score = ScoreData.rjust(3,"-")
            elif ScoreType == "B1B":                                        # Batsman 1 Balls Faced
                pcsB1B = ScoreData
            elif ScoreType == "B1K":                                        # Batsman 1 On Strike?
                pcsB1K = ScoreData
            elif ScoreType == "B2N":                                        # Batsman 2 Name
                pcsBBN = ScoreData
                pcsBBN = pcsBBN[:10]
            elif ScoreType == "B2S":                                        # Batsman 1 score formatted with leading dashes for blanks
                Bat2Score = ScoreData.rjust(3,"-")
            elif ScoreType == "B2B":                                        # Batsman 2 Balls Faced
                pcsB2B = ScoreData
            elif ScoreType == "B2K":                                        # Batsman 2 On Strike?
                pcsB2K = ScoreData
            elif ScoreType == "F1N":                                        # Current Bowler Name
                pcsF1N = ScoreData
                pcsF1N = pcsF1N[:10]
            elif ScoreType == "F1S":                                        # Current Bowler  Figures
                pcsF1S = ScoreData
            elif ScoreType == "F2N":                                        # Current Bowler Name
                pcsF2N = ScoreData
                pcsF2N = pcsF2N[:10]
            elif ScoreType == "F2S":                                        # Previous Bowler Figures
                pcsF2S = ScoreData
            elif ScoreType == "LWK":                                        # Last Wicket
                pcsLWK = ScoreData
            elif ScoreType == "DLT":                                        # Duckworth Lewis Target
                pcsDLT = ScoreData
            elif ScoreType == "DLP":                                        # Duckworth Lewis Par Score at end of current over
                pcsDLP = ScoreData               
            # New code for enhanced Spectator board END 
            else:
                print(WriteReturn + " (not used)")
           #lets not send an update to the scoreboard
            UpdateScoreboard = False

            if UpdateScoreboard:
                Scoreboard = "4," + BatTotal + "," + Wickets + "," + Overs + "," + Target + "#"
                print(Scoreboard)
                #with serial.Serial("/dev/ttyACM0", 57600, timeout=1) as arduino:
                #    # time.sleep(0.1) #wait for serial to open
                #    if arduino.isOpen():
                #        print("{} connected!".format(arduino.port))
                #        arduino.write(Scoreboard.encode())
                #        print("Data Sent: " + Scoreboard)
                #        arduino.close
            update_scoreboard()
        except:
            print(sys.exc_info()[0], "occurred")
       
       
class UartService(Service):
    def __init__(self, bus, index):
        Service.__init__(self, bus, index, UART_SERVICE_UUID, True)
        self.add_characteristic(RxCharacteristic(bus, 1, self))

class Application(dbus.service.Object):
    def __init__(self, bus):
        self.path = '/'
        self.services = []
        dbus.service.Object.__init__(self, bus, self.path)

    def get_path(self):
        return dbus.ObjectPath(self.path)

    def add_service(self, service):
        self.services.append(service)

    @dbus.service.method(DBUS_OM_IFACE, out_signature='a{oa{sa{sv}}}')
    def GetManagedObjects(self):
        response = {}
        for service in self.services:
            response[service.get_path()] = service.get_properties()
            chrcs = service.get_characteristics()
            for chrc in chrcs:
                response[chrc.get_path()] = chrc.get_properties()
        return response

class UartApplication(Application):
    def __init__(self, bus):
        Application.__init__(self, bus)
        self.add_service(UartService(bus, 0))

class UartAdvertisement(Advertisement):
    def __init__(self, bus, index):
        Advertisement.__init__(self, bus, index, 'peripheral')
        self.add_service_uuid(UART_SERVICE_UUID)
        self.add_local_name(LOCAL_NAME)
        self.include_tx_power = True

def find_adapter(bus):
    remote_om = dbus.Interface(bus.get_object(BLUEZ_SERVICE_NAME, '/'),
                              DBUS_OM_IFACE)
    objects = remote_om.GetManagedObjects()
    for o, props in objects.items():
        if LE_ADVERTISING_MANAGER_IFACE in props and GATT_MANAGER_IFACE in props:
            return o
        print('Skip adapter:', o)
    return None

def main():
    global mainloop
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
    bus = dbus.SystemBus()
    adapter = find_adapter(bus)
    if not adapter:
        print('BLE adapter not found')
        return

    service_manager = dbus.Interface(
                                bus.get_object(BLUEZ_SERVICE_NAME, adapter),
                                GATT_MANAGER_IFACE)
    ad_manager = dbus.Interface(bus.get_object(BLUEZ_SERVICE_NAME, adapter),
                                LE_ADVERTISING_MANAGER_IFACE)

    app = UartApplication(bus)
    adv = UartAdvertisement(bus, 0)

    mainloop = GLib.MainLoop()

    service_manager.RegisterApplication(app.get_path(), {},
                                        reply_handler=register_app_cb,
                                        error_handler=register_app_error_cb)
    ad_manager.RegisterAdvertisement(adv.get_path(), {},
                                    reply_handler=register_ad_cb,
                                    error_handler=register_ad_error_cb)
    try:
        mainloop.run()
    except KeyboardInterrupt:
        adv.Release()

if __name__ == '__main__':
    main()

Tony.Rogers

Posts : 31
Join date : 2017-11-30

Back to top Go down

Problem with Play Cricket Scorer app and Overs Bowled not always updating Empty Re: Problem with Play Cricket Scorer app and Overs Bowled not always updating

Post by targett2023 Mon May 06, 2024 9:36 am

PatrickT1 wrote:Just thinking back to the testing I did before to send the info to the PCS support team - I was able to replicate this problem without the Pi (and therefore the uart_peripheral.py script) in the mix.

I used an Amazon Fire tablet running PCS app, and cloned the scoreboard device using nrfConnect app on my phone (Galaxy S23).

The OVB field would still be missing occasionally, although all the other fields were sent reliably.

As I said to the support team, this rules out the scoreboard hardware and software, and points the finger at their app, but they were having none of it.

Even multiple presses of the Refresh Scoreboard button in the PCS app would not send the OVB field.

Any thoughts?


Don't make too many assumptions. How do you know the nRF app isn't just subject to the same flaw. The flaw here, and it is PCS's imo, is the way they send the data. If you pulse messages closely together instead of sending all in one packet, there's always going to be combinations of hardware that probably miss. The bluestooth stack is complicated, and even if your processing code is efficient, there is a lot going on under the hood, deeper down in the stack. That said, there could be something wrong on the PCS side. In terriers, they definitely do not deduct the -5, or whatever, until the ball after the wicket is taken i.e. it is one ball out of sync. I haven't noticed OVB. I experienced it to different degrees with differing fields and differing devices.

targett2023

Posts : 17
Join date : 2023-06-23

Back to top Go down

Problem with Play Cricket Scorer app and Overs Bowled not always updating Empty Re: Problem with Play Cricket Scorer app and Overs Bowled not always updating

Post by PatrickT1 Mon May 06, 2024 9:50 am

I'm starting to think effort is better spent on being able to correct the scoreboard when the problem happens, rather than fixing the problem.

I have been using the uart_peripheral script to update the save.txt file that the Web page used to save the scores, so that the Web interface is in sync with the score sent from PCS via Bluetooth. It is crude but works. Need to test if I can update via the Web interface whilst PCS is scoring and see what happens. As it stands it will probably overwrite any changes after each ball comes from PCS - I'll have to tweak that.

Thanks both for all your input so far - I have to retrieve the Pi from the scoreboard to play with it, so it'll take me a bit of time to get anywhere with this, but I'll report back.

PatrickT1

Posts : 30
Join date : 2023-06-23
Location : Collingbourne CC

Back to top Go down

Problem with Play Cricket Scorer app and Overs Bowled not always updating Empty Re: Problem with Play Cricket Scorer app and Overs Bowled not always updating

Post by Tony.Rogers Mon May 06, 2024 10:03 am

PatrickT1 wrote:I'm starting to think effort is better spent on being able to correct the scoreboard when the problem happens, rather than fixing the problem.

I have been using the uart_peripheral script to update the save.txt file that the Web page used to save the scores, so that the Web interface is in sync with the score sent from PCS via Bluetooth. It is crude but works.  Need to test if I can update via the Web interface whilst PCS is scoring and see what happens. As it stands it will probably overwrite any changes after each ball comes from PCS - I'll have to tweak that.

Thanks both for all your input so far - I have to retrieve the Pi from the scoreboard to play with it, so it'll take me a bit of time to get anywhere with this, but I'll report back.


saving to save.txt is a great idea, could you copy that bit of code here for me please.

Tony.Rogers

Posts : 31
Join date : 2017-11-30

Back to top Go down

Problem with Play Cricket Scorer app and Overs Bowled not always updating Empty Re: Problem with Play Cricket Scorer app and Overs Bowled not always updating

Post by PatrickT1 Mon May 06, 2024 10:08 am

Will do - can't right now, but will do later.

PatrickT1

Posts : 30
Join date : 2023-06-23
Location : Collingbourne CC

Back to top Go down

Problem with Play Cricket Scorer app and Overs Bowled not always updating Empty Re: Problem with Play Cricket Scorer app and Overs Bowled not always updating

Post by PatrickT1 Tue May 07, 2024 11:05 am

@Tony - here's the code snippet I used in the original uart-peripheral.py script to save to save.txt:

Code:

            if UpdateScoreboard:
 #               Scoreboard = "4," + BatA + "," + BatTotal + "," + BatB + "," + Wickets + "," + Overs + "," + Target + "#"
                Scoreboard = "4," + BatTotal + "," + Overs + "," + Wickets + "#"
                TmpSaveTxt = BatTotal + Wickets + Overs + Target
                SaveTxt = TmpSaveTxt.replace("-" , "0")
                print(SaveTxt)
                print(Scoreboard)
                f = open("/var/www/html/save.txt", "w")
                f.write(SaveTxt)
                f.close()
                with serial.Serial("/dev/ttyACM0", 57600, timeout=1) as arduino:
                    # time.sleep(0.1) #wait for serial to open
                    if arduino.isOpen():
                        print("{} connected!".format(arduino.port))
                        arduino.write(Scoreboard.encode())
                        print("Data Sent: " + Scoreboard)
                        arduino.close

I might have had to do something with the permissions on the save.txt file to allow that process to write to it.

Then in the web page dochecks function I added this:

Code:

.....
      // Check to see if the scoreboard needs updating
      function dochecks() {

         if(updatetimer=="done") {
            //There are no updates pending, don't do anything
            // Check to see if anything has been saved into save.txt
            $.ajax({
                        type: "GET",
                        url: "save.txt",
            cache: false,
             success: function (data) {
               if(data.length>0) { // If it has, update the scores with the saved data
                  total=Number(data.substring(0, 3));
                  wickets=Number(data.substring(3, 4));
                  overs=Number(data.substring(4, 6));
                  target=Number(data.substring(6, 9));

                  $('#total_count').html(pad(total,3));
                  $('#wickets_count').html(pad(wickets,1));
                  $('#overs_count').html(pad(overs,2));
                  $('#target_count').html(pad(target,3));


               } else {
                  // If there isn't anything, don't do anything
               }
               },
               });
.....


It's crude, but it means the web page shows the score from Play Cricket.

If you change the score on the web page, it will save it to the save.txt file via the scoreboard.php script, but if PCS changes the save.txt file then it will revert, so there's the chance of changes clashing from each side. I need to give this some thought as to how to correct the scoreboard if PCS is not sending data correctly.

PatrickT1

Posts : 30
Join date : 2023-06-23
Location : Collingbourne CC

Tony.Rogers likes this post

Back to top Go down

Problem with Play Cricket Scorer app and Overs Bowled not always updating Empty Re: Problem with Play Cricket Scorer app and Overs Bowled not always updating

Post by PatrickT1 Tue May 07, 2024 11:12 am

@target2023 - Thanks for your code - I'll give it a try.

I started testing again last night, and with the old code and the new version of PCS that was released in April the problem is worse than it ever was. I now can't connect my Fire Tablet, and with my Galaxy S23 the OVB is missing more often than it is there.

Using ChatGPT I got a working adaptation of the original uart-peripheral.py working in a multithreaded manner using queues, but it made no difference to OVB appearing or not. Using a demo match I scored about 8 overs without correctly receiving the OVB field, even using the refresh scoreboard function.

I'll give your code a try and see how that goes.

Thanks for your help - I'll keep you posted with progress.

PatrickT1

Posts : 30
Join date : 2023-06-23
Location : Collingbourne CC

Back to top Go down

Problem with Play Cricket Scorer app and Overs Bowled not always updating Empty Re: Problem with Play Cricket Scorer app and Overs Bowled not always updating

Post by PatrickT1 Tue May 07, 2024 12:24 pm

@target2023 - wow, that was easy - thank you so much.

I've got that running and just done a test. In scoring 6 overs, it missed OVB on only 2 balls, which is a big improvement.

There's obviously an issue somewhere, but I'll give this method a go and see how I get on. Thanks again.



PatrickT1

Posts : 30
Join date : 2023-06-23
Location : Collingbourne CC

Back to top Go down

Problem with Play Cricket Scorer app and Overs Bowled not always updating Empty Re: Problem with Play Cricket Scorer app and Overs Bowled not always updating

Post by PatrickT1 Tue May 07, 2024 3:35 pm

@target2023 - I'm trying to get your toy_bluetooth_server.py and toy_scoreboard.py to run at boot.

I edited the previous btscoreboard.sh, which is (at least should be) run at boot to point to the new py scripts rather than the old uart-peripheral.py, but I can't see anything in any logs to tell me it hasn't worked, but I don't see the "My Scoreboard" from PCS.

Any ideas what I need to do to get it running from boot?

Thanks for your help

PatrickT1

Posts : 30
Join date : 2023-06-23
Location : Collingbourne CC

Back to top Go down

Problem with Play Cricket Scorer app and Overs Bowled not always updating Empty Re: Problem with Play Cricket Scorer app and Overs Bowled not always updating

Post by Stacey Tue May 07, 2024 9:44 pm

Hi all,
just adding a reply on here so I get notifications of the outcome. Boards in bits at the moment, and too couldn't connect via the Bluetooth following the latest update. No idea how to code etc so going to lurk and see what you magicians come up with. Thanks! Stacey

Stacey

Posts : 29
Join date : 2021-09-04

Back to top Go down

Problem with Play Cricket Scorer app and Overs Bowled not always updating Empty Re: Problem with Play Cricket Scorer app and Overs Bowled not always updating

Post by targett2023 Wed May 08, 2024 9:44 am

PatrickT1 wrote:@target2023 - I'm trying to get your toy_bluetooth_server.py and toy_scoreboard.py to run at boot.

I edited the previous btscoreboard.sh, which is (at least should be) run at boot to point to the new py scripts rather than the old uart-peripheral.py, but I can't see anything in any logs to tell me it hasn't worked, but I don't see the "My Scoreboard" from PCS.

Any ideas what I need to do to get it running from boot?  

Thanks for your help

Sorry to steepen your learning curve further, but you should probably ditch using cron. It isn't exactly obsolete or deprecated, but people tend to use linux services these days. I don't know if you have ever used the following command, or something like it:

Code:
sudo systemctl bluetooth restart

Bluetooth is an example of a linux service. The nice thing with services is you can specify dependencies easily, so you can say do not start service A before service B. The issue you are more than likely seeing is that the cron starts the client socket before the server socket and it fails, just as it would if you did it manually in that order.

Anyway, it really isn't difficult. Just try google for an example. It just involves writing a small config file that tells systemctl where to find your exe, placing the config in the right location, and then enabling the service to start at boot.

targett2023

Posts : 17
Join date : 2023-06-23

Back to top Go down

Problem with Play Cricket Scorer app and Overs Bowled not always updating Empty Re: Problem with Play Cricket Scorer app and Overs Bowled not always updating

Post by Sponsored content


Sponsored content


Back to top Go down

Page 1 of 2 1, 2  Next

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum