├── .github └── workflows │ ├── docker-image.yml │ └── pylint.yml ├── .gitignore ├── .pylintrc ├── Dynamic_RDS.php ├── Dynamic_RDS_Engine.py ├── LICENSE ├── QN8066.py ├── README.md ├── Transmitter.py ├── api.php ├── basicI2C.py ├── basicMQTT.py ├── basicPWM.py ├── callbacks.py ├── config.py ├── images ├── README.md ├── RPi_to_QN8066_cable.jpeg ├── pi_transmitter_setup1.jpg ├── pi_transmitter_setup2.jpg ├── pi_transmitter_setup3.jpg ├── radio_board.jpeg ├── radio_board_and_pi_pinout.jpeg ├── radio_board_pinout.jpeg ├── radio_board_w_screen.jpeg └── raspberry_pi_connection.jpeg ├── menu.inc ├── pluginInfo.json ├── scripts ├── fpp_install.sh ├── fpp_uninstall.sh ├── paho_install.sh └── src_Dynamic_RDS_config.sh └── settings.json /.github/workflows/docker-image.yml: -------------------------------------------------------------------------------- 1 | name: FPP Latest Docker Test 2 | 3 | on: 4 | workflow_dispatch: 5 | #pull_request: 6 | #branches: [ "main" ] 7 | 8 | jobs: 9 | 10 | docker-test: 11 | 12 | runs-on: ubuntu-latest 13 | container: 14 | image: falconchristmas/fpp:latest 15 | ports: 16 | - 80 17 | steps: 18 | - uses: actions/checkout@v4 19 | name: Build the Docker image 20 | 21 | -------------------------------------------------------------------------------- /.github/workflows/pylint.yml: -------------------------------------------------------------------------------- 1 | name: Pylint 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | strategy: 9 | matrix: 10 | python-version: ["3.11.2"] 11 | steps: 12 | - uses: actions/checkout@v4 13 | - name: Set up Python ${{ matrix.python-version }} 14 | uses: actions/setup-python@v5 15 | with: 16 | python-version: ${{ matrix.python-version }} 17 | - name: Install dependencies 18 | run: | 19 | python -m pip install --upgrade pip 20 | pip install pylint 21 | - name: Analysing the code with pylint 22 | run: | 23 | pylint --fail-under=9.5 $(git ls-files '*.py') 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | *.py.swp 132 | -------------------------------------------------------------------------------- /.pylintrc: -------------------------------------------------------------------------------- 1 | [MASTER] 2 | indent-string=' ' 3 | max-line-length = 250 4 | 5 | [MESSAGES CONTROL] 6 | disable = missing-docstring, invalid-name, fixme, bare-except, broad-exception-caught, import-error 7 | -------------------------------------------------------------------------------- /Dynamic_RDS.php: -------------------------------------------------------------------------------- 1 | 2 |
3 |

Status

4 | open($zipName, ZipArchive::CREATE)!==TRUE) { 15 | echo '
Unable to create ZIP file to download
'; 16 | exit; 17 | } 18 | if (is_file($dynRDSDir . "/Dynamic_RDS_callbacks.log")) { 19 | $zip->addFile($dynRDSDir . "/Dynamic_RDS_callbacks.log", "Dynamic_RDS_callbacks.log"); 20 | } 21 | if (is_file($dynRDSDir . "/Dynamic_RDS_Engine.log")) { 22 | $zip->addFile($dynRDSDir . "/Dynamic_RDS_Engine.log", "Dynamic_RDS_Engine.log"); 23 | } 24 | if (is_file($configDirectory . "/plugin.Dynamic_RDS")) { 25 | $zip->addFile($configDirectory . "/plugin.Dynamic_RDS", "plugin.Dynamic_RDS"); 26 | } 27 | if (is_file("/boot/config.txt")) { 28 | $zip->addFile("/boot/config.txt", "old-config.txt"); 29 | } 30 | if (is_file("/boot/firmware/config.txt")) { 31 | $zip->addFile("/boot/firmware/config.txt", "config.txt"); 32 | } 33 | if (is_file("/boot/uEnv.txt")) { 34 | $zip->addFile("/boot/uEnv.txt", "uEnv.txt"); 35 | } 36 | $zip->addFromString('Dynamic_RDS_version.txt', shell_exec('git -C ' . $dynRDSDir . ' rev-parse --short HEAD')); 37 | $zip->close(); 38 | if (is_file($zipName)) { 39 | header("Content-Disposition: attachment; filename=\"" . basename($zipName) . "\""); 40 | header("Content-Type: application/octet-stream"); 41 | header("Content-Length: ".filesize($zipName)); 42 | header("Connection: close"); 43 | flush(); 44 | readfile($zipName); 45 | unlink($zipName); 46 | } 47 | exit; 48 | } 49 | 50 | $errorDetected = false; 51 | 52 | if (empty(trim(shell_exec("dpkg -s python3-smbus | grep installed")))) { 53 | echo '
python3-smbus is missing
'; 54 | $errorDetected = true; 55 | } 56 | 57 | $i2cbus = -1; 58 | if ($isBBB && file_exists('/dev/i2c-2')) { 59 | $i2cbus = 2; 60 | } elseif (file_exists('/dev/i2c-0')) { 61 | $i2cbus = 0; 62 | } elseif (file_exists('/dev/i2c-1')) { 63 | $i2cbus = 1; 64 | } else { 65 | echo '
Unable to find an I2C bus - On RPi, check /boot/config.txt for I2C entry
'; 66 | $errorDetected = true; 67 | } 68 | 69 | $engineRunning = true; 70 | if (empty(trim(shell_exec("ps -ef | grep python.*Dynamic_RDS_Engine.py | grep -v grep")))) { 71 | sleep(1); 72 | if (empty(trim(shell_exec("ps -ef | grep python.*Dynamic_RDS_Engine.py | grep -v grep")))) { 73 | echo '
Dynamic RDS Engine is not running - Check logs for errors - Restart of FPPD is recommended
'; 74 | $engineRunning = false; 75 | $errorDetected = true; 76 | } 77 | } 78 | 79 | $transmitterType = ''; 80 | $transmitterAddress = ''; 81 | if ($i2cbus != -1) { 82 | if (trim(shell_exec("sudo i2cget -y " . $i2cbus . " 0x21 2>&1")) != "Error: Read failed") { 83 | $transmitterType = 'QN8066'; 84 | $transmitterAddress = '0x21'; 85 | } elseif (trim(shell_exec("sudo i2cget -y " . $i2cbus . " 0x63 2>&1")) != "Error: Read failed") { 86 | $transmitterType = 'Si4713'; 87 | $transmitterAddress = '0x63'; 88 | } else { 89 | echo '
No transmitter detected on I2C bus ' . $i2cbus . ' at addresses 0x21 or 0x63
'; 90 | echo 'Power cycle or reset of transmitter is recommended. SSH into FPP and run i2cdetect -y -r ' . $i2cbus . ' to check I2C status
'; 91 | $errorDetected = true; 92 | } 93 | } 94 | 95 | if ($isRPi && isset($pluginSettings['DynRDSQN8066PIPWM']) && $pluginSettings['DynRDSQN8066PIPWM'] == 1 && is_numeric(strpos($pluginSettings['DynRDSAdvPIPWMPin'], ','))) { 96 | if (shell_exec("lsmod | grep 'snd_bcm2835.*1\>'")) { 97 | echo '
On-board sound card appears active and will interfere with hardware PWM. Try a reboot first, next toggle the Enable PI Hardware PWM setting below and reboot. If issues persist check /boot/config.txt and comment out dtparam=audio=on
'; 98 | } 99 | if (empty(shell_exec("lsmod | grep pwm")) || !file_exists('/sys/class/pwm/pwmchip0')) { 100 | echo '
Hardware PWM has not been loaded. Try a reboot first, next toggle the Enable PI Hardware PWM setting below and reboot. If issues persist then check /boot/config.txt and add dtoverlay=pwm
'; 101 | } 102 | } 103 | 104 | $i2cBusType = 'hardware'; 105 | if ($isRPi) { 106 | if (isset($pluginSettings['DynRDSAdvPISoftwareI2C']) && $pluginSettings['DynRDSAdvPISoftwareI2C'] == 1) { 107 | $i2cBusType = 'software'; 108 | if (shell_exec("lsmod | grep i2c_bcm2835")) { 109 | echo '
Hardware I2C appears active. Try a reboot first, next toggle the Use PI Software I2C setting below and reboot. If issues persist check /boot/config.txt and comment out dtparam=i2c_arm=on
'; 110 | $i2cBusType = 'hardware'; 111 | } 112 | if (empty(shell_exec("lsmod | grep i2c_gpio"))) { 113 | echo '
Software I2C has not been loaded. Try a reboot first, next toggle the Use PI Software I2C setting below and reboot. If issues persist then check /boot/config.txt and add dtoverlay=i2c-gpio,i2c_gpio_sda=2,i2c_gpio_scl=3,i2c_gpio_delay_us=4,bus=1
'; 114 | } 115 | } else { 116 | if (shell_exec("lsmod | grep i2c_gpio")) { 117 | echo '
Software I2C appears active. Try a reboot first, next toggle the Use PI Software I2C setting below and reboot. If issues persist check /boot/config.txt and comment out dtoverlay=i2c-gpio,i2c_gpio_sda=2,i2c_gpio_scl=3,i2c_gpio_delay_us=4,bus=1
'; 118 | $i2cBusType = 'software'; 119 | } 120 | if (empty(shell_exec("lsmod | grep i2c_bcm2835"))) { 121 | echo '
Hardware I2C has not been loaded. Try a reboot first, next toggle the Use PI Software I2C setting below and reboot. If issues persist then check /boot/config.txt and add dtparam=i2c_arm=on
'; 122 | } 123 | } 124 | } 125 | 126 | if ($engineRunning || $transmitterType != '') { 127 | echo '
'; 128 | if ($engineRunning) { 129 | echo '
Dynamic RDS Engine is running
'; 130 | } 131 | if ($transmitterType != '') { 132 | echo '
Detected ' . $transmitterType . ' on I2C ' . $i2cBusType . ' bus ' . $i2cbus . ' at address ' . $transmitterAddress . '
'; 133 | } 134 | echo '
'; 135 | } 136 | ?> 137 | 138 | 169 | 170 | 173 |

RDS Style Text Guide

174 | Values from File Tags or Track Info 175 | 181 | Main Playlist Section Values 182 | 184 | Any static text can be used
185 | | (pipe) will split between RDS groups, like a line break
186 | [ ] creates a subgroup such that if ANY substitution in the subgroup is emtpy, the entire subgroup is omitted
187 | Use a \ in front of | { } [ or ] to display those characters
188 | End of the style text will implicitly function as a line break
189 | ", "", 1, "Dynamic_RDS"); 190 | 191 | PrintSettingGroup("DynRDSTransmitterSettings", "", "", 1, "Dynamic_RDS"); 192 | 193 | PrintSettingGroup("DynRDSAudioSettings", "", "indicates a live change to transmitter, no FPP restart required", 1, "Dynamic_RDS", "DynRDSFastUpdate"); 194 | 195 | PrintSettingGroup("DynRDSPowerSettings", "", "", 1, "Dynamic_RDS", "DynRDSPiBootUpdate"); 196 | 197 | PrintSettingGroup("DynRDSPluginActivation", "", "Set when the transmitter is active", 1, "Dynamic_RDS"); 198 | 199 | if (!(is_file('/bin/mpc') || is_file('/usr/bin/mpc'))) { 200 | echo '

MPC / After Hours Music

Install the After Hours Music Player Plugin to enabled. MPC not detected

'; 201 | } else { 202 | PrintSettingGroup("DynRDSmpc", "", "Pull RDS data from MPC / After Hours Music plugin when idle", 1, "Dynamic_RDS", "DynRDSFastUpdate"); 203 | } 204 | 205 | if ($settings['MQTTHost'] == '') { 206 | echo '

MQTT

Requires that MQTT has been configured under FPP Settings -> MQTT

'; 207 | } elseif (!(file_exists('/usr/lib/python3/dist-packages/paho') || file_exists('/usr/local/lib/python3.9/dist-packages/paho'))) { 208 | echo '

MQTT

python3-paho-mqtt is needed to enable MQTT support
'; 209 | } else { 210 | PrintSettingGroup("DynRDSmqtt", "", "Broker Host is " . $settings['MQTTHost'] . ":" . $settings['MQTTPort'] . "", 1, "Dynamic_RDS", ""); 211 | } 212 | 213 | PrintSettingGroup("DynRDSLogLevel", "", "", 1, "Dynamic_RDS", "DynRDSFastUpdate"); 214 | ?> 215 | 216 |

View Logs

217 |
218 |

Dynamic_RDS_callbacks.log 219 |

220 |

Dynamic_RDS_Engine.log 221 |

222 |
223 |
224 | 225 |

Report an Issue

226 |
227 |

228 |

229 | 230 |

231 |

Create a new issue at https://github.com/ShadowLight8/Dynamic_RDS/issues, describe what you're seeing, and attach the zip file.

232 | Zip file includes: 233 | 239 |
240 |
241 | 242 | 245 | 246 | -------------------------------------------------------------------------------- /Dynamic_RDS_Engine.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import logging 4 | import json 5 | import os 6 | import errno 7 | import atexit 8 | import socket 9 | import sys 10 | import subprocess 11 | import unicodedata 12 | from time import sleep 13 | from datetime import date, datetime, timedelta 14 | from urllib.request import urlopen 15 | from urllib.parse import quote 16 | 17 | from config import config, read_config_from_file 18 | from QN8066 import QN8066 19 | from basicMQTT import basicMQTT, pahoMQTT 20 | 21 | def logUnhandledException(eType, eValue, eTraceback): 22 | logging.error("Unhandled exception", exc_info=(eType, eValue, eTraceback)) 23 | sys.excepthook = logUnhandledException 24 | 25 | @atexit.register 26 | def cleanup(): 27 | try: 28 | logging.debug('Cleaning up fifo') 29 | os.unlink(fifo_path) 30 | except: 31 | pass 32 | try: 33 | transmitter.basicPWM.shutdown() 34 | if mqtt.connected: 35 | mqtt.disconnect() 36 | except: 37 | pass 38 | logging.info('Exiting') 39 | 40 | # ================================== 41 | # Configuration defaults and loading 42 | # ================================== 43 | 44 | def read_config(): 45 | read_config_from_file() 46 | 47 | # TODO: Move this QN8066 specific code to that class? Like a config tweak in QN8066? 48 | # Convert DynRDSQN8066Gain into DynRDSQN8066InputImpedance, DynRDSQN8066DigitalGain, and DynRDSQN8066BufferGain 49 | totalGain = int(config['DynRDSQN8066Gain']) + 15 50 | config['DynRDSQN8066DigitalGain'] = totalGain % 3 51 | 52 | if totalGain < 24: 53 | config['DynRDSQN8066InputImpedance'] = 3 - totalGain // 6 54 | config['DynRDSQN8066BufferGain'] = totalGain % 6 // 3 55 | else: 56 | config['DynRDSQN8066InputImpedance'] = 0 57 | config['DynRDSQN8066BufferGain'] = totalGain % 18 // 3 58 | 59 | if not (os.path.exists('/bin/mpc') or os.path.exists('/usr/bin/mpc')): 60 | config['DynRDSmpcEnable'] = 0 61 | 62 | logging.getLogger().setLevel(config['DynRDSEngineLogLevel']) 63 | logging.info('Config %s', config) 64 | 65 | # =============================== 66 | # Processing FPP Data to RDS Data 67 | # =============================== 68 | 69 | def updateRDSData(): 70 | # Take the data from FPP and the configuration to build the actual RDS string 71 | logging.info('New RDS Data') 72 | logging.debug('RDS Values %s', rdsValues) 73 | 74 | # TODO: DynRDSRTSize functionally works, but I think this should source from the RTBuffer class post initialization 75 | transmitter.updateRDSData(rdsStyleToString(config['DynRDSPSStyle'], 8), rdsStyleToString(config['DynRDSRTStyle'], int(config['DynRDSRTSize']))) 76 | 77 | if config['DynRDSmqttEnable'] == '1': 78 | mqttStatus = {} 79 | mqttStatus['PStext'] = transmitter.PStext 80 | mqttStatus['RTtext'] = transmitter.RTtext 81 | mqttStatus['PSfragments'] = transmitter.PS.fragments 82 | mqttStatus['RTfragments'] = transmitter.RT.fragments 83 | mqttStatus['RDSValues'] = rdsValues 84 | mqtt.publish('status', json.dumps(mqttStatus, indent=8)) 85 | 86 | def rdsStyleToString(rdsStyle, groupSize): 87 | outputRDS = [] 88 | squStart = -1 89 | skip = 0 90 | 91 | try: 92 | for i, v in enumerate(rdsStyle): 93 | #print("i {} - v {} - squStart {} - skip {} - outputRDS {}".format(i,v,squStart,skip,outputRDS)) 94 | if skip: 95 | skip -= 1 96 | elif v == '\\' and i < len(rdsStyle) - 1: 97 | skip += 1 98 | outputRDS.append(rdsStyle[i+1]) 99 | elif v == '[': 100 | squStart = len(outputRDS) # Track on the outputRDS where the square bracket started in case we have to clean up 101 | elif v == ']' and squStart != -1: # End of square bracket mode, append to output and reset 102 | squStart = -1 103 | elif v == '|': 104 | chunkLength = groupSize - sum(len(s) for s in outputRDS) % groupSize 105 | if chunkLength != groupSize: 106 | outputRDS.append(' ' * chunkLength) 107 | elif v == '{' and i < len(rdsStyle) - 2 and rdsStyle[i+2] == '}': 108 | if squStart != -1 and not rdsValues.get(rdsStyle[i:i+3],''): # In square brackets and value is empty? 109 | del outputRDS[squStart:] # Remove output back to start of square bracket group 110 | skip += rdsStyle.index(']', i + 3) - i - 1 # Using index to throw if no ] by the end of rdsStyle - Done building in this case 111 | else: 112 | skip += 2 113 | # Normalize Unicode characters to their nearest ascii characters 114 | # Other character substitutions could be done here 115 | outputRDS.append(unicodedata.normalize('NFKD', rdsValues.get(rdsStyle[i:i+3], '')).encode('ascii', 'ignore').decode()) 116 | else: 117 | outputRDS.append(v) 118 | except ValueError: 119 | pass # Expected when index doesn't find a ] 120 | except Exception: 121 | logging.exception('rdsStyleToString') 122 | 123 | outputRDS = ''.join(outputRDS) 124 | logging.debug('RDS Data [%s]', outputRDS) 125 | return outputRDS 126 | 127 | # =============== 128 | # Main code start 129 | # =============== 130 | 131 | # Setup logging 132 | script_dir = os.path.dirname(os.path.abspath(sys.argv[0])) 133 | #logging.basicConfig(stream=sys.stderr, level=logging.DEBUG, format='%(asctime)s:%(name)s:%(levelname)s:%(message)s') 134 | logging.basicConfig(filename=script_dir + '/Dynamic_RDS_Engine.log', level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s', datefmt='%H:%M:%S') 135 | 136 | # Adding in excessive log level below debug for very noisy items 137 | # Allow for debug to be reasonable 138 | # Debug is as deep as most people would want 139 | EXCESSIVE = 5 140 | 141 | def excessive(msg, *args, **kwargs): 142 | if logging.getLogger().isEnabledFor(EXCESSIVE): 143 | logging.log(EXCESSIVE, msg, *args, **kwargs) 144 | 145 | logging.addLevelName(5, 'EXCESSIVE') 146 | logging.EXCESSIVE = EXCESSIVE 147 | logging.excessive = excessive 148 | logging.Logger.excessive = excessive 149 | 150 | logging.info('--- %s', date.today()) 151 | 152 | # Establish lock via socket or exit if failed 153 | try: 154 | lock_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) 155 | lock_socket.bind('\0Dynamic_RDS_Engine') 156 | logging.debug('Lock created') 157 | except: 158 | logging.error('Unable to create lock. Another instance of Dynamic_RDS_Engine.py running?') 159 | sys.exit(1) 160 | 161 | # Setup fifo 162 | fifo_path = script_dir + "/Dynamic_RDS_FIFO" 163 | try: 164 | logging.debug('Setting up read side of fifo %s', fifo_path) 165 | os.mkfifo(fifo_path) 166 | except OSError as oe: 167 | if oe.errno != errno.EEXIST: 168 | raise 169 | logging.debug('Fifo already exists') 170 | 171 | # Global RDS Values 172 | rdsValues = {'{T}': '', '{A}': '', '{B}': '', '{G}': '', '{N}': '','{L}': '', '{C}': '', '{P}': ''} 173 | 174 | # TODO: Check for existance of After Hours plugin by dir 175 | # TODO: Check for existance of mpc program to get status 176 | 177 | # ========= 178 | # Main Loop 179 | # ========= 180 | transmitter = None 181 | mqtt = None 182 | activePlaylist = False 183 | nextMPCUpdate = datetime.now() 184 | 185 | # Check if new information is in the FIFO and process accordingly 186 | with open(fifo_path, 'r', encoding='UTF-8') as fifo: 187 | while True: 188 | line = fifo.readline().rstrip() 189 | if len(line) > 0: 190 | logging.debug('line %s', line) 191 | if line == 'EXIT': 192 | logging.info('Processing exit') 193 | transmitter.shutdown() # TODO: Can fail if transmitter wasn't set - Can fix with an if statement or look into using Transmitter base class initially 194 | mqtt.disconnect() 195 | sys.exit() 196 | 197 | elif line == 'RESET': 198 | logging.info('Processing reset') 199 | read_config() 200 | mqtt.publish('config', json.dumps(config, indent=8)) 201 | transmitter.reset() 202 | if config['DynRDSStart'] == "FPPDStart": 203 | transmitter.startup() 204 | 205 | elif line == 'INIT': # From --list with callback.py 206 | logging.info('Processing init') 207 | read_config() 208 | 209 | transmitter = None 210 | if config['DynRDSTransmitter'] == "QN8066": 211 | transmitter = QN8066() 212 | elif config['DynRDSTransmitter'] == "Si4713": 213 | transmitter = None # To be implemented later 214 | 215 | if transmitter is None: 216 | logging.error('Transmitter not set. Check Transmitter Type.') 217 | continue 218 | 219 | if config['DynRDSmqttEnable'] == "1": 220 | try: 221 | mqtt = pahoMQTT() 222 | except Exception: 223 | logging.exception('Unable to initialize pahoMQTT') 224 | mqtt = basicMQTT() 225 | else: 226 | mqtt = basicMQTT() 227 | mqtt.connect() 228 | mqtt.publish('ready', '1') 229 | mqtt.publish('config', json.dumps(config, indent=8)) 230 | 231 | updateRDSData() 232 | 233 | if config['DynRDSStart'] == "FPPDStart": 234 | transmitter.startup() 235 | 236 | elif line == 'UPDATE': 237 | read_config() 238 | mqtt.publish('config', json.dumps(config, indent=8)) 239 | if (transmitter is not None and transmitter.active): 240 | for key in rdsValues: 241 | rdsValues[key] = '' 242 | updateRDSData() 243 | transmitter.update() 244 | 245 | elif line == 'START': 246 | logging.info('Processing start') 247 | if config['DynRDSStart'] == "PlaylistStart" or not transmitter.active: 248 | transmitter.startup() 249 | activePlaylist = True 250 | 251 | elif line == 'STOP': 252 | logging.info('Processing stop') 253 | for key in rdsValues: 254 | rdsValues[key] = '' 255 | updateRDSData() 256 | activePlaylist = False 257 | 258 | if config['DynRDSStop'] == "PlaylistStop": 259 | transmitter.shutdown() 260 | logging.info('Transmitter stopped') 261 | 262 | elif line.startswith('MAINLIST'): 263 | logging.info('Processing MainPlaylist') 264 | playlist_name = line[8:] # TODO: Need to keep track of last playlist name to reduce overhead? 265 | if playlist_name != '': 266 | logging.debug('Playlist Name: %s', playlist_name) 267 | playlist_length = 1 268 | if '.' not in playlist_name: # Case where a sequence is directly run from the scheduler or status page, it ends in .fseq and . is not allowed in regular playlist names 269 | try: 270 | with urlopen(f'http://localhost/api/playlist/{quote(playlist_name)}') as response: 271 | data = response.read() 272 | playlist_length = len(json.loads(data)['mainPlaylist']) 273 | except Exception: 274 | logging.exception("Playlist Length") 275 | logging.debug('Playlist Length: %s', playlist_length) 276 | rdsValues['{C}'] = str(playlist_length) 277 | else: 278 | rdsValues['{C}'] = '' 279 | 280 | elif line[0] == 'P': 281 | logging.debug('Processing playlist position') 282 | rdsValues['{P}'] = line[1:] 283 | updateRDSData() # Always follows MAINLIST, so only a single update is needed 284 | 285 | # rdsValues that need additional parsing 286 | elif line[0] == 'L': 287 | logging.debug('Processing length') 288 | if line[1:] != '0': 289 | rdsValues['{L}'] = f'{int(line[1:])//60}:{int(line[1:])%60:02d}' 290 | else: 291 | rdsValues['{L}'] = '' 292 | #tracklength = max(int(line[1:10]) - max(int(config['DynRDSPSUpdateRate']), int(config['DynRDSRTUpdateRate'])), 1) 293 | #logging.debug('Length %s', int(tracklength)) 294 | 295 | # TANL is always sent together with L being last item, so we only need to update the RDS Data once with the new values 296 | # TODO: This will likely change as more data is added, so a new way will have to be determined 297 | updateRDSData() 298 | #activePlaylist = True # TODO: Is this needed still? 299 | transmitter.status() 300 | 301 | # All of the rdsValues that are stored as is 302 | else: 303 | rdsValues['{'+line[0]+'}'] = line[1:] 304 | 305 | elif transmitter is not None and transmitter.active and config['DynRDSEnableRDS'] == "1": 306 | transmitter.sendNextRDSGroup() 307 | # TODO: Determine when track length is done to reset RDS 308 | # TODO: Could add 1 sec to length, so normally track change will update data rather than time expiring. Reset should only happen when playlist is stopped? 309 | 310 | if not activePlaylist and transmitter is not None and transmitter.active and config['DynRDSmpcEnable'] == "1" and datetime.now() > nextMPCUpdate: 311 | logging.debug('Processing mpc') 312 | nextMPCUpdate = datetime.now() + timedelta(seconds=12) 313 | # TODO: Error handling might be needed here if the mpc execution has an issue 314 | # TODO: Future idea to handle multiple fields from mpc, but I've not seen them used yet. [{A}%artist%][{T}%title%][{N}%track%] 315 | mpcLatest = subprocess.run(['mpc', 'current', '-f', '%title%'], stdout=subprocess.PIPE, check=False).stdout.decode('utf-8').strip() 316 | if rdsValues['{T}'] != mpcLatest: 317 | rdsValues['{T}'] = mpcLatest 318 | updateRDSData() 319 | 320 | if transmitter is None or not transmitter.active: 321 | logging.debug('Sleeping...') 322 | sleep(3) 323 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /QN8066.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import sys 3 | import os 4 | from time import sleep 5 | from datetime import datetime 6 | 7 | from config import config 8 | from basicI2C import basicI2C 9 | from basicPWM import basicPWM, hardwarePWM, softwarePWM, hardwareBBBPWM 10 | from Transmitter import Transmitter 11 | 12 | class QN8066(Transmitter): 13 | def __init__(self): 14 | logging.info('Initializing QN8066 transmitter') 15 | super().__init__() 16 | self.I2C = basicI2C(0x21) 17 | self.PS = self.PSBuffer(self, ' ', int(config['DynRDSPSUpdateRate'])) 18 | self.RT = self.RTBuffer(self, ' ', int(config['DynRDSRTUpdateRate'])) 19 | self.basicPWM = basicPWM() 20 | 21 | def startup(self): 22 | logging.info('Starting QN8066 transmitter') 23 | 24 | tempReadValue = self.I2C.read(0x06, 1)[0]>>2 25 | if tempReadValue != 0b1101: 26 | logging.error('Chip ID value is %s instead of 13. Is this a QN8066 chip?', tempReadValue) 27 | sys.exit(-1) 28 | 29 | #tempReadValue = self.I2C.read(0x0a, 1)[0]>>4 30 | #if (tempReadvalue != 0): # TO TEST 31 | # logging.warning('Chip state is {} instead of 0 (Standby). Was startup already run?'.format(tempReadValue)) 32 | 33 | # Reset everything 34 | self.I2C.write(0x00, [0b11100011], True) 35 | sleep(0.2) 36 | 37 | # Setup expected clock source and div 38 | self.I2C.write(0x02, [0b00010000], True) 39 | self.I2C.write(0x07, [0b11101000, 0b00001011], True) 40 | 41 | # Set frequency from config 42 | # (Frequency - 60) / 0.05 43 | tempFreq = int((float(config['DynRDSFrequency'])-60)/0.05) 44 | self.I2C.write(0x19, [0b00100000 | tempFreq>>8], True) 45 | self.I2C.write(0x1b, [0b11111111 & tempFreq], True) 46 | 47 | # Enable RDS TX and set pre-emphasis 48 | if config['DynRDSPreemphasis'] == "50us": 49 | self.I2C.write(0x01, [0b00000000 | int(config['DynRDSEnableRDS'])<<6]) 50 | else: 51 | self.I2C.write(0x01, [0b00000001 | int(config['DynRDSEnableRDS'])<<6]) 52 | 53 | # Exit standby, enter TX 54 | self.I2C.write(0x00, [0b00001011], True) 55 | sleep(0.2) 56 | 57 | # Reset aud_pk 58 | self.I2C.write(0x24, [0b10000000 | int(max(24,(int(config['DynRDSQN8066ChipPower']) - 70.2) // 0.91))]) 59 | self.I2C.write(0x24, [0b00000000 | int(max(24,(int(config['DynRDSQN8066ChipPower']) - 70.2) // 0.91))]) 60 | 61 | self.update() 62 | super().startup() 63 | 64 | # With everything started up, select and enable needed PWM type 65 | if os.getenv('FPPPLATFORM', '') == 'Raspberry Pi': 66 | if config['DynRDSQN8066PIPWM'] == '1': 67 | if config['DynRDSAdvPIPWMPin'] in {'18,2' , '12,4'}: 68 | self.basicPWM = hardwarePWM(0) 69 | self.basicPWM.startup(18300, int(config['DynRDSQN8066AmpPower'])) 70 | elif config['DynRDSAdvPIPWMPin'] in {'13,4' , '19,2'}: 71 | self.basicPWM = hardwarePWM(1) 72 | self.basicPWM.startup(18300, int(config['DynRDSQN8066AmpPower'])) 73 | else: 74 | self.basicPWM = softwarePWM(int(config['DynRDSAdvPIPWMPin'])) 75 | self.basicPWM.startup(10000, int(config['DynRDSQN8066AmpPower'])) 76 | #else: 77 | #self.basicPWM.startup() 78 | elif os.getenv('FPPPLATFORM', '') == 'BeagleBone Black': 79 | self.basicPWM = hardwareBBBPWM(config['DynRDSAdvBBBPWMPin']) 80 | self.basicPWM.startup(18300, int(config['DynRDSQN8066AmpPower'])) 81 | #else: 82 | #self.basicPWM.startup() 83 | 84 | def update(self): 85 | # Try without 0x25 0b01111101 - TX Freq Dev of 86.25KHz 86 | # Try without 0x26 0b00111100 - RDS Freq Dev of 21KHz 87 | 88 | # TODO: New option to configure soft clip level 3db is the default (also 4.5db, 6db, and 9db) 89 | self.I2C.write(0x27, [0b00111010], True) 90 | 91 | # Stop Auto Gain Correction (AGC), which introduces obvious poor sounding audio changes 92 | if config['DynRDSQN8066AGC'] == '0': 93 | self.I2C.write(0x6e, [0b10110111], True) 94 | # TODO: Else if it is re-enabled 95 | 96 | # TX gain changes and input impedance 97 | self.I2C.write(0x28, [int(config['DynRDSQN8066SoftClipping'])<<7 | int(config['DynRDSQN8066BufferGain'])<<4 | int(config['DynRDSQN8066DigitalGain'])<<2 | int(config['DynRDSQN8066InputImpedance'])], True) 98 | #self.I2C.write(0x28, [0b01011011]) 99 | 100 | # PWM get updated 101 | self.basicPWM.update(int(config['DynRDSQN8066AmpPower'])) 102 | 103 | def shutdown(self): 104 | logging.info('Stopping QN8066 transmitter') 105 | # Exit TX, Enter standby 106 | self.I2C.write(0x00, [0b00100011]) 107 | super().shutdown() 108 | 109 | # With everything stopped, shutdown PWM 110 | self.basicPWM.shutdown() 111 | 112 | def reset(self, resetdelay=1): 113 | # Used to restart the transmitter 114 | self.shutdown() 115 | del self.I2C 116 | self.I2C = basicI2C(0x21) 117 | sleep(resetdelay) 118 | self.startup() 119 | 120 | def status(self): 121 | aud_pk = self.I2C.read(0x1a, 1)[0]>>3 & 0b1111 122 | fsm = self.I2C.read(0x0a,1)[0]>>4 123 | # TODO: Check frequency? 0x19 1:0 + 0x1b 124 | # TODO: Add PWM status if active - Might move elsewhere if PWM gets located to a single file 125 | 126 | logging.info('Status - State %s (expect 10) - Audio Peak %s (target <= 14)', fsm, aud_pk) 127 | 128 | # Reset aud_pk 129 | self.I2C.write(0x24, [0b10000000 | int(max(24,(int(config['DynRDSQN8066ChipPower']) - 70.2) // 0.91))]) 130 | self.I2C.write(0x24, [0b00000000 | int(max(24,(int(config['DynRDSQN8066ChipPower']) - 70.2) // 0.91))]) 131 | super().status() 132 | 133 | def updateRDSData(self, PSdata='', RTdata=''): 134 | logging.debug('QN8066 updateRDSData') 135 | super().updateRDSData(PSdata, RTdata) 136 | self.PS.updateData(PSdata) 137 | self.RT.updateData(RTdata) 138 | 139 | def sendNextRDSGroup(self): 140 | # If more advanced mixing of RDS groups is needed, this is where it would occur 141 | logging.excessive('QN8066 sendNextRDSGroup') 142 | self.PS.sendNextGroup() 143 | self.RT.sendNextGroup() 144 | 145 | def transmitRDS(self, rdsBytes): 146 | # Specific to QN 8036 and 8066 chips 147 | rdsStatusByte = self.I2C.read(0x01, 1)[0] 148 | rdsSendToggleBit = rdsStatusByte >> 1 & 0b1 149 | rdsSentStatusToggleBit = self.I2C.read(0x1a, 1)[0] >> 2 & 0b1 150 | logging.excessive('Transmit %s - Send Bit %s - Status Bit %s', ' '.join('0x{:02x}'.format(a) for a in rdsBytes), rdsSendToggleBit, rdsSentStatusToggleBit) 151 | self.I2C.write(0x1c, rdsBytes) 152 | self.I2C.write(0x01, [rdsStatusByte ^ 0b10]) 153 | # RDS specifications indicate 87.6ms to send a group 154 | # sleep is a bit less, plus time to read the status toggle bit 155 | sleep(0.087) 156 | if (self.I2C.read(0x1a, 1)[0] >> 2 & 1) == rdsSentStatusToggleBit: 157 | i = 0 158 | while (self.I2C.read(0x1a, 1)[0] >> 2 & 1) == rdsSentStatusToggleBit: 159 | logging.excessive('Waiting for rdsSentStatusToggleBit to flip') 160 | sleep(0.01) 161 | i += 1 162 | if i > 50: 163 | logging.error('rdsSentStatusToggleBit failed to flip') 164 | # RDS has failed to update, reset the QN8066 165 | self.reset() 166 | break 167 | 168 | class PSBuffer(Transmitter.RDSBuffer): 169 | # Sends RDS type 0B groups - Program Service 170 | # Fragment size of 8, Groups send 2 characters at a time 171 | def __init__(self, outer, data, delay=4): 172 | super().__init__(data, 8, 2, delay) 173 | # Include outer for the common transmitRDS function that both PSBuffer and RTBuffer use 174 | self.outer = outer 175 | 176 | def updateData(self, data): 177 | super().updateData(data) 178 | # Adjust last fragment to make all 8 characters long 179 | self.fragments[-1] = self.fragments[-1].ljust(self.frag_size) 180 | logging.info('PS %s', self.fragments) 181 | 182 | def sendNextGroup(self): 183 | if self.currentGroup == 0 and (datetime.now() - self.lastFragmentTime).total_seconds() >= self.delay: 184 | self.currentFragment = (self.currentFragment + 1) % len(self.fragments) 185 | self.lastFragmentTime = datetime.now() 186 | logging.debug('Send PS Fragment \'%s\'', self.fragments[self.currentFragment]) 187 | 188 | rdsBytes = [self.pi_byte1, self.pi_byte2, 0b10<<2 | self.pty>>3, (0b00111 & self.pty)<<5 | self.currentGroup, self.pi_byte1, self.pi_byte2] 189 | rdsBytes.append(ord(self.fragments[self.currentFragment][self.currentGroup * self.group_size])) 190 | rdsBytes.append(ord(self.fragments[self.currentFragment][self.currentGroup * self.group_size + 1])) 191 | 192 | self.outer.transmitRDS(rdsBytes) 193 | self.currentGroup = (self.currentGroup + 1) % (self.frag_size // self.group_size) 194 | 195 | class RTBuffer(Transmitter.RDSBuffer): 196 | # Sends RDS type 2A groups - RadioText 197 | # Max fragment size of 64, Groups send 4 characters at a time 198 | def __init__(self, outer, data, delay=7): 199 | self.ab = 0 200 | super().__init__(data, int(config['DynRDSRTSize']), 4, delay) 201 | self.outer = outer 202 | 203 | def updateData(self, data): 204 | super().updateData(data) 205 | # Add 0x0d to end of last fragment to indicate RT is done 206 | # TODO: This isn't quite correct - Should put 0x0d where a break is indicated in the rdsStyleText 207 | if len(self.fragments[-1]) < self.frag_size: 208 | self.fragments[-1] += chr(0x0d) 209 | self.ab = not self.ab 210 | logging.info('RT %s', self.fragments) 211 | 212 | def sendNextGroup(self): 213 | # Will block for ~80-90ms for RDS Group to be sent 214 | # Check time, if it has been long enough AND a full RT fragment has been sent, move to next fragment 215 | # Flip A/B bit, send next group, if last group set full RT sent flag 216 | # Need to make sure full RT group has been sent at least once before moving on 217 | if self.currentGroup == 0 and (datetime.now() - self.lastFragmentTime).total_seconds() >= self.delay: 218 | self.currentFragment = (self.currentFragment + 1) % len(self.fragments) 219 | self.lastFragmentTime = datetime.now() 220 | self.ab = not self.ab 221 | # Change \r (0x0d) to be [0d] for logging so it is visible in case of debugging 222 | logging.debug('Send RT Fragment \'%s\'', self.fragments[self.currentFragment].replace('\r','<0d>')) 223 | 224 | # TODO: Seems like this could be improved 225 | rdsBytes = [self.pi_byte1, self.pi_byte2, 0b1000<<2 | self.pty>>3, (0b00111 & self.pty)<<5 | self.ab<<4 | self.currentGroup] 226 | rdsBytes.append(ord(self.fragments[self.currentFragment][self.currentGroup * self.group_size])) 227 | rdsBytes.append(ord(self.fragments[self.currentFragment][self.currentGroup * self.group_size + 1]) if len(self.fragments[self.currentFragment]) - self.currentGroup * self.group_size >= 2 else 0x20) 228 | rdsBytes.append(ord(self.fragments[self.currentFragment][self.currentGroup * self.group_size + 2]) if len(self.fragments[self.currentFragment]) - self.currentGroup * self.group_size >= 3 else 0x20) 229 | rdsBytes.append(ord(self.fragments[self.currentFragment][self.currentGroup * self.group_size + 3]) if len(self.fragments[self.currentFragment]) - self.currentGroup * self.group_size >= 4 else 0x20) 230 | 231 | self.outer.transmitRDS(rdsBytes) 232 | self.currentGroup += 1 233 | if self.currentGroup * self.group_size >= len(self.fragments[self.currentFragment]): 234 | self.currentGroup = 0 235 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Dynamic_RDS - FM Transmitter Plugin for Falcon Player 2 | 3 | Created for Falcon Player 6.0+ (FPP) as a plugin to generate RDS (radio data system) messages similar to what is seen from typical FM stations. The RDS messages are fully customizable with static text, breaks, and grouping along with the supported file tag data fields of title, artist, album, genre, track number, and track length, as well as main playlist position and item count. Currently, the plugin supports the QN8066 chip and there are plans to add the Si4173 in the future. The chips are controlled via the I2C bus. 4 | 5 | ## Recommended QN8066 transmitter board 6 | > [!IMPORTANT] 7 | > There are other similar looking boards, so double check for the QN8066 chip. For a detailed look at identifying QN8066 boards, check out [Spectraman's video](https://www.youtube.com/watch?v=i8re0nc_FdY&t=1017s). 8 | 9 | [Aliexpress link to purchase QN8066 FM Transmitter](https://a.aliexpress.com/_mLTpVqO) 10 | 11 | ![Radio Board with Screen](images/radio_board_w_screen.jpeg) 12 | ![Radio Board](images/radio_board.jpeg) 13 | ![Radio Board Pinout](images/radio_board_pinout.jpeg) 14 | 15 | ## Antenna 16 | The QN8066 transmitter board needs an antenna for safe operations. 17 | 18 | * Small bench testing option - https://www.amazon.com/gp/product/B07K7DBVX9 19 | * 1/4 wave ground plane antenna calculator - https://m0ukd.com/calculators/quarter-wave-ground-plane-antenna-calculator/ 20 | * Show ready option 1/4 wave - https://www.amazon.com/Transmitter-Professional-87-108mhz-0-5w-100w-Waterproof/dp/B09NDPY4JG 21 | * Inexpensive 1/4 wave option - https://www.aliexpress.us/item/2251832695723994.html 22 | * BNC to BNC cable - https://www.amazon.com/gp/product/B0BVVVRYZL/) 23 | 24 | (More detail to be added) 25 | 26 | ## Cables, Connectors, and Shielding 27 | > [!CAUTION] 28 | > Do not run the PWM wire along side the I2C wires. During testing this caused failures in the I2C commands as soon as PWM was enabled. 29 | 30 | ### Connector info 31 | * The connection on the transmitter board is a 5-pin JST-XH type connector, 2.54mm. 32 | * The Raspberry Pis use a female Dupont connector and we recommended using a 2 x 6 block connector. 33 | * The BeagleBone Blacks (BBB) use a male Dupont connector (recommendation pending BBB support work in progress). 34 | 35 | If you are comfortable with crimping and making connectors, here are examples of what to use 36 | * JST-XH connectors - https://www.amazon.com/dp/B015Y6JOUG 37 | * Dupont connectors - https://www.amazon.com/dp/B0774NMT1S 38 | * Single kit with both JST-XH and Dupont connectors - https://www.amazon.com/dp/B09Q5MPM7H/ 39 | * JST-XH kit with Crimping Tool - https://www.amazon.com/gp/product/B094XSF2GK 40 | 41 | Pre-crimped wires are also an options 42 | * JST-XH Pre-crimped wires - https://www.amazon.com/dp/B0BW9TJN21 43 | * Dupont Pre-crimped wires - https://www.amazon.com/dp/B07GD1W1VL 44 | 45 | ### Cable for a Raspberry Pi 46 | 47 | ![Raspberry Pi Connection](images/raspberry_pi_connection.jpeg) 48 | ![Raspberry Pi to Radio](images/radio_board_and_pi_pinout.jpeg) 49 | ![Custom RPi to QN8066 Cable](images/RPi_to_QN8066_cable.jpeg) 50 | 51 | The green PWM wire runs next to yellow 3.3V and orange GND wire until right before the end to eliminate issue with interference. Keeping the cable as short as possible helps to reduce interference. 52 | 53 | ### Cable for a BeagleBone Black (BBB) 54 | (Support for the BBB is still in progress) 55 | 56 | ### Shielding and RF interference 57 | Given the nature of an FM transmitter, interference is potential problem. This interference commonly shows up as I2C errors which become more frequent as transmitter power increases. Moving the antenna away from the RPi/BBB and the transmitter board can reduce this. A significantly more robust setup it to locate the RPi/BBB and transmitter board inside a grounded, metal case such as was done by @chrkov here: 58 | ![Grounded case setup](images/pi_transmitter_setup1.jpg) 59 | ![Grounded case setup](images/pi_transmitter_setup2.jpg) 60 | 61 | ## Using Hardware PWM on Raspberry Pi 62 | The recommended QN8066 transmitter board can take a PWM signal to increase its power output. Be sure to comply with all applicable laws related to FM broadcasts. 63 | 64 | > [!CAUTION] 65 | > Do not run the PWM wire along side the I2C wires. During testing this caused failures in the I2C commands as soon as PWM was enabled. 66 | 67 | On the Raspberry Pi, in order to use the hardware PWM, the built-in analog audio must be disabled and an external USB sound card or DAC is required. The built-in audio uses both hardware PWM channels to generate the audio, so PWM cannot be used for other purposes when enabled. Software PWM is also an option, but at an increased CPU cost and a decrease in duty cycle accuracy. 68 | 69 | From the Dynamic RDS configuration page, under the Power Settings, enable PWM. 70 | 71 | This will automatically modify the /boot/config.txt: 72 | 1. Comment out all ```dtparm=audio=on``` lines with a # 73 | 2. Add the line ```dtoverlay=pwm,pin=18,func=2``` by default 74 | Under the Advanced Options at the bottom of the configuration page, the output pin can be selected. This is also where Software PWM can be selected on most other pins. 75 | 76 | > [!TIP] 77 | > Don't forget to change the Audio Output Device in the FPP Settings to use the USB sound card or DAC 78 | 79 | ## Integration with FPP After Hours Music Plugin 80 | The Dynamic RDS plugin has the ability to work in conjunction with the [FPP After Hours Music Plugin](https://github.com/jcrossbdn/fpp-after-hours) to provide RDS Data from an internet stream of music. The information from the stream is populated in the Title field. 81 | 82 | Once the After Hours Music Plugin is installed, the integration can be enabled on the Dynamic RDS configuration pages in the MPC / After Hours Music section. 83 | 84 | ![MPC-After-Hours](https://user-images.githubusercontent.com/23623446/201971100-7a213ef5-a22d-4e76-a545-8c8c9724a9e0.JPG) 85 | 86 | ## Scripting Plugin Changes 87 | It is an option to use scripts to change Dynamic RDS option value. As an example, this could be used to change the PS and/or RT style text to be different during the show verses after. The following is a bash script that can update the style text and have the plugin start using it without restarting FPP. 88 | ``` 89 | #!/bin/bash 90 | curl -d 'Merry|Christ-| -mas!|{T}|{A}|[{N} of {C}]' -X POST http://localhost/api/plugin/Dynamic_RDS/settings/DynRDSPSStyle 91 | curl -d 'Merry Christmas! {T}[ by {A}]|[Track {N} of {C}]' -X POST http://localhost/api/plugin/Dynamic_RDS/settings/DynRDSRTStyle 92 | curl http://localhost/api/plugin/Dynamic_RDS/FastUpdate 93 | ``` 94 | The single quotes around the style text in the script are important so the Linux shell (bash) won't try to interpret what is in there. This example could be saved as a file in the media/scripts folder and then use it with the scheduler (via Command -> Run Script) or playlists. 95 | 96 | ## Troubleshooting 97 | ### Transmitter not working (for the recommended QN8066 board) 98 | - Verify transmitter is working on it's own 99 | - Connect the original screen, connect antenna, and 12v power 100 | - Connected to audio input near the screen connector 101 | - Check for transmission with a radio. If not, transmitter maybe bad and need to be replaced 102 | - Remove power, then disconnect screen 103 | 104 | - Verify transmitter is working with RPi/BBB 105 | - With everything powered off, connect the transmitter to the RPi/BBB for 3v3, GND, SDA, and SCL 106 | - Do NOT connect the PWM pin 107 | - Verify each wire is connected correctly 3v3, GND, SDA, and SCL 108 | - Power up the RPi/BBB 109 | - Transmitter will power up from power supplied by RPi/BBB (Do NOT connect 12v power yet) 110 | - Verify the transmitter shows up on the I2C bus at 0x21 111 | - Either from the Dynamic RDS config page OR 112 | - SSH into the RPi ```i2cdetect -y 1``` and run or on BBB run ```i2cdetect -r -y 2``` 113 | - If transmitter does not show up 114 | - Double check each wire is connectioned correctly 3v3, GND, SDA, and SCL 115 | - No really, go double check! It can happen to anyone! :) 116 | - Check each wire's continuity to make sure there isn't a break 117 | 118 | ### Transmitter's RDS not working well 119 | - Enable Debug logging for the Engine 120 | - Check for read and/or write errors in Dynamic_RDS_Engine.log 121 | - If too many errors happen, then I2C fails and the Engine exits 122 | - Reduce the Amp Power 123 | - Try using Software I2C 124 | - Enclose the RPi/BBB and transmitter in a grounded, metal box with the antenna outside of the box 125 | - Check connection and wire continuity between RPi/BBB 126 | - Disconnect transmitter 12v power if connected and check I2C bus with `i2cdetect -y 1` 127 | - If errors happen at random 128 | - Make sure the PWM wire does NOT run along side the I2C wires, interference can occur 129 | - Try to lower the Chip Power and Amp Power, RF interference can impact I2C 130 | - Move the antenna further away from the transmitter board and RPi/BBB 131 | -------------------------------------------------------------------------------- /Transmitter.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from time import sleep 3 | from datetime import datetime 4 | 5 | from config import config 6 | 7 | # =================== 8 | # Transmitter Classes 9 | # =================== 10 | # Generic representation of a Transmitter with a common interface 11 | # Includes a common RDSBuffer class 12 | # Specific implementations of both are expected by child classes 13 | 14 | # Transmitter 15 | # RDSBuffer 16 | # 17 | # QN8066 (Transmitter) 18 | # PSBuffer (RDSBuffer) 19 | # RTBuffer (RDSBuffer) 20 | 21 | class Transmitter: 22 | def __init__(self): 23 | # Common class init 24 | self.active = False 25 | self.PStext = '' 26 | self.RTtext = '' 27 | 28 | def startup(self): 29 | # Common elements for starting up the transmitter for broadcast 30 | self.active = True 31 | 32 | def update(self): 33 | # For settings that can be updated dynamically 34 | pass 35 | 36 | def shutdown(self): 37 | # Common elements for shutting down the transmitter from broadcast 38 | self.active = False 39 | 40 | def reset(self, resetdelay=1): 41 | # Used to restart the transmitter 42 | self.shutdown() 43 | sleep(resetdelay) 44 | self.startup() 45 | 46 | def status(self): 47 | # Expected to be defined by child class 48 | pass 49 | 50 | def updateRDSData(self, PSdata='', RTdata=''): 51 | # Expected to be defined by child class 52 | self.PStext = PSdata 53 | self.RTtext = RTdata 54 | 55 | def sendNextRDSGroup(self): 56 | # Expected to be defined by child class 57 | pass 58 | 59 | # ============================================= 60 | # RDS Buffer Class (Inner class of Transmitter) 61 | # ============================================= 62 | # This holds a string of RDS data to send, how much can be displayed at a time, how many chars per RDS group, and how long between updates 63 | # Typically, two instances are created by a transmitter, one for the PS groups and one for the RT groups 64 | # Data - Entire string to show on RDS Screen over time - updateData called once per track, resets all counters 65 | # Fragment - What's on a single RDS Screen - Holds 8 for PS or 32/64 chars for RT - sendNextGroup tracks time to determine when to move to next fragment 66 | # Group - Single RDS Data Packet - Holds 2 or 4 chars - sendNextGroup called multiple times per second 67 | 68 | class RDSBuffer: 69 | def __init__(self, data='', frag_size=0, group_size=0, delay=4): 70 | logging.debug('RDSBuffer init') 71 | self.frag_size = frag_size 72 | self.group_size = group_size 73 | self.delay = delay 74 | self.pi_byte1 = int('0x' + config['DynRDSPICode'][0:2], 16) 75 | self.pi_byte2 = int('0x' + config['DynRDSPICode'][2:4], 16) 76 | self.pty = int(config['DynRDSPty']) 77 | self.updateData(data) 78 | self.fragments = [] 79 | self.currentFragment = 0 80 | self.lastFragmentTime = 0 81 | self.currentGroup = 0 82 | 83 | def updateData(self, data): 84 | logging.debug('RDSBuffer updateData') 85 | self.fragments = [] 86 | self.currentFragment = 0 87 | self.lastFragmentTime = datetime.now() 88 | self.currentGroup = 0 89 | for i in range(0, len(data), self.frag_size): 90 | self.fragments.append(data[i : i + self.frag_size]) 91 | 92 | def sendNextGroup(self): 93 | # Expected to be defined by child class 94 | pass 95 | -------------------------------------------------------------------------------- /api.php: -------------------------------------------------------------------------------- 1 | 'GET', 'endpoint' => 'FastUpdate', 'callback' => 'DynRDSFastUpdate'), 6 | array('method' => 'POST', 'endpoint' => 'PiBootChange/:SettingName', 'callback' => 'DynRDSPiBootChange'), 7 | array('method' => 'POST', 'endpoint' => 'ScriptStream', 'callback' => 'DynRDSScriptStream') 8 | ); 9 | return $endpoints; 10 | } 11 | 12 | function DynRDSFastUpdate() { 13 | shell_exec("sudo /home/fpp/media/plugins/Dynamic_RDS/callbacks.py --update"); 14 | } 15 | 16 | function DynRDSPiBootChange() { 17 | $settingName = params('SettingName'); 18 | $myPluginSettings = json_decode(file_get_contents('php://input'), true); 19 | 20 | switch ($settingName) { 21 | case 'DynRDSAdvPISoftwareI2C': 22 | if (strcmp($myPluginSettings[$settingName],'1') == 0) { 23 | exec("sudo sed -i -e 's/^dtparam=i2c_arm=on/#dtparam=i2c_arm=on/' /boot/firmware/config.txt"); 24 | exec("sudo sed -i -e '/^#dtparam=i2c_arm=on/a dtoverlay=i2c-gpio,i2c_gpio_sda=2,i2c_gpio_scl=3,i2c_gpio_delay_us=4,bus=1' /boot/firmware/config.txt"); 25 | } else { 26 | exec("sudo sed -i -e '/^dtoverlay=i2c-gpio,i2c_gpio_sda=2,i2c_gpio_scl=3,i2c_gpio_delay_us=4,bus=1/d' /boot/firmware/config.txt"); 27 | exec("sudo sed -i -e 's/^#dtparam=i2c_arm=on/dtparam=i2c_arm=on/' /boot/firmware/config.txt"); 28 | } 29 | break; 30 | 31 | case 'DynRDSQN8066PIPWM': 32 | if (strcmp($myPluginSettings[$settingName],'1') == 0) { 33 | exec("sudo sed -i -e 's/^dtparam=audio=on/#dtparam=audio=on/' /boot/firmware/config.txt"); 34 | if (is_numeric(strpos($myPluginSettings['DynRDSAdvPIPWMPin'], ','))) { 35 | exec("sudo sed -i -e '/^#dtparam=audio=on/a dtoverlay=pwm,pin=" . str_replace(",", ",func=", $myPluginSettings['DynRDSAdvPIPWMPin']) . "' /boot/firmware/config.txt"); 36 | } 37 | } else { 38 | exec("sudo sed -i -e '/^dtoverlay=pwm/d' /boot/firmware/config.txt"); 39 | exec("sudo sed -i -e 's/^#dtparam=audio=on/dtparam=audio=on/' /boot/firmware/config.txt"); 40 | } 41 | break; 42 | 43 | case 'DynRDSAdvPIPWMPin': 44 | if (is_numeric(strpos($myPluginSettings['DynRDSAdvPIPWMPin'], ','))) { 45 | exec("sudo sed -i -e 's/^#dtoverlay=pwm/dtoverlay=pwm/' /boot/firmware/config.txt"); 46 | exec("sudo sed -i -e '/^dtoverlay=pwm/c dtoverlay=pwm,pin=" . str_replace(",", ",func=", $myPluginSettings['DynRDSAdvPIPWMPin']) . "' /boot/firmware/config.txt"); 47 | } else { 48 | exec("sudo sed -i -e 's/^dtoverlay=pwm/#dtoverlay=pwm/' /boot/firmware/config.txt"); 49 | } 50 | break; 51 | 52 | case 'DynRDSQN8066AmpPower': 53 | DynRDSFastUpdate(); 54 | break; 55 | 56 | default: 57 | DynRDSFastUpdate(); 58 | } 59 | } 60 | 61 | function DynRDSScriptStream() { 62 | $postData = json_decode(file_get_contents('php://input'), true); 63 | 64 | DisableOutputBuffering(); 65 | 66 | switch ($postData['script']) { 67 | case 'dependencies': 68 | system('~/media/plugins/Dynamic_RDS/scripts/fpp_install.sh', $return_val); 69 | break; 70 | case 'python3-paho-mqtt': 71 | system('~/media/plugins/Dynamic_RDS/scripts/paho_install.sh', $return_val); 72 | break; 73 | default: 74 | return "\nUnknown script\n"; 75 | } 76 | return "\nDone\n"; 77 | } 78 | ?> 79 | -------------------------------------------------------------------------------- /basicI2C.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | import sys 4 | from time import sleep 5 | import smbus 6 | 7 | # =============== 8 | # Basic I2C Class 9 | # =============== 10 | # Used by the Transmitter child classes (if they are i2c), but could also be used on its own if needed 11 | # Assuming SMBus of 1 on most modern hardware - Can check /dev/i2c-* for available buses 12 | class basicI2C(): 13 | def __init__(self, address, bus=1): 14 | self.address = address 15 | # Bus 1 is Modern RPis, Bus 2 is BBB, Bus 0 is older RPis 16 | if os.path.exists('/dev/i2c-2') or os.path.exists('/sys/class/i2c-2'): 17 | bus = 2 18 | elif os.path.exists('/dev/i2c-0') or os.path.exists('/sys/class/i2c-0'): 19 | bus = 0 20 | logging.info('Using i2c bus %s', bus) 21 | try: 22 | self.bus = smbus.SMBus(bus) 23 | except Exception: 24 | logging.exception("SMBus Init Error") 25 | sleep(2) # TODO: Is this sleep still needed for the bus to init? 26 | 27 | def write(self, address, values, isFatal = False): 28 | # Simple i2c write - Always takes an list, even for 1 byte 29 | logging.excessive('I2C write at 0x%02x of %s', address, ' '.join('0x{:02x}'.format(a) for a in values)) 30 | for i in range(8): 31 | try: 32 | self.bus.write_i2c_block_data(self.address, address, values) 33 | except Exception: 34 | logging.exception("write_i2c_block_data error") 35 | if i >= 1: 36 | sleep(i * .25) 37 | continue 38 | else: 39 | break 40 | else: 41 | logging.error("failed to write after multiple attempts") 42 | if isFatal: 43 | sys.exit(-1) 44 | 45 | def read(self, address, num_bytes, isFatal = False): 46 | # Simple i2c read - Always returns a list 47 | for i in range(8): 48 | try: 49 | retVal = self.bus.read_i2c_block_data(self.address, address, num_bytes) 50 | logging.excessive('I2C read at 0x%02x of %s byte(s) returned %s', address, num_bytes, ' '.join('0x{:02x}'.format(a) for a in retVal)) 51 | return retVal 52 | except Exception: 53 | logging.exception("read_i2c_block_data error") 54 | if i >= 1: 55 | sleep(i * .25) 56 | continue 57 | else: 58 | break 59 | else: 60 | logging.error("failed to read after multiple attempts") 61 | if isFatal: 62 | sys.exit(-1) 63 | return [] 64 | -------------------------------------------------------------------------------- /basicMQTT.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import logging 4 | import json 5 | from urllib.request import urlopen 6 | from urllib.parse import quote 7 | 8 | class basicMQTT: 9 | def __init__(self): 10 | self.connected = False 11 | 12 | def connect(self): 13 | self.connected = True 14 | 15 | def publish(self, subtopic, value, qos=1, retain=True): 16 | pass 17 | 18 | def disconnect(self): 19 | self.connected = False 20 | 21 | def status(self): 22 | pass 23 | 24 | class pahoMQTT(basicMQTT): 25 | # Command line to monitor: mosquitto_sub -v -d -h localhost -t "#" 26 | def __init__(self): 27 | logging.info('Initializing pahoMQTT') 28 | global paho 29 | import paho.mqtt.client as paho 30 | 31 | # Pull in FPP setting needed for MQTT via API 32 | self.MQTTSettings = {} 33 | self.MQTTSettings['HostName'] = self.readAPISetting('HostName')['value'] 34 | 35 | mqttInfo = self.readAPISetting('MQTTHost') 36 | self.MQTTSettings['MQTTHost'] = mqttInfo['value'] 37 | 38 | if self.MQTTSettings['MQTTHost'] == '': 39 | logging.warning('MQTT Broker Host is not set. Check FPP Settings -> MQTT -> Broker Host value') 40 | raise Exception('Missing MQTT Host') 41 | 42 | for setting in mqttInfo['children']['*']: 43 | settingInfo = self.readAPISetting(setting) 44 | self.MQTTSettings[setting] = settingInfo['value'] if 'value' in settingInfo else '' 45 | 46 | if self.MQTTSettings['MQTTPort'] == '': 47 | logging.warning('MQTT Port value is missing, using default of 1883') 48 | self.MQTTSettings['MQTTPort'] = '1883' 49 | 50 | logging.debug('MQTT Settings %s', self.MQTTSettings) 51 | 52 | self.topicBase = f'falcon/player/{self.MQTTSettings["HostName"]}/plugin/Dynamic_RDS' 53 | if self.MQTTSettings["MQTTPrefix"] != '': 54 | self.topicBase = f'{self.MQTTSettings["MQTTPrefix"]}/{self.topicBase}' 55 | 56 | self.client = paho.Client() 57 | self.client.enable_logger() 58 | super().__init__() 59 | 60 | def connect(self): 61 | logging.info('Connecting to broker with pahoMQTT') 62 | self.client.on_connect = self.on_connect 63 | if self.MQTTSettings['MQTTUsername'] != '': 64 | self.client.username_pw_set(self.MQTTSettings['MQTTUsername'], self.MQTTSettings['MQTTPassword']) 65 | self.client.will_set(f'{self.topicBase}/ready', '-1', 0, True) 66 | self.client.connect_async(self.MQTTSettings['MQTTHost'], int(self.MQTTSettings['MQTTPort'])) 67 | self.client.loop_start() 68 | 69 | def publish(self, subtopic, value, qos=1, retain=True): 70 | self.client.publish(f'{self.topicBase}/{subtopic}', value, qos, retain) 71 | 72 | def disconnect(self): 73 | logging.info('Disconnecting from broker') 74 | self.publish('ready', '0') 75 | self.client.loop_stop() 76 | self.client.disconnect() 77 | super().disconnect() 78 | 79 | def status(self): 80 | pass 81 | 82 | def on_connect(self, client, userdata, flags, rc): 83 | logging.info('Connected to broker with pahoMQTT') 84 | # TODO: Deal with rc for failures 85 | super().connect() 86 | 87 | def on_publish(self): 88 | pass 89 | 90 | def readAPISetting(self, settingName): 91 | try: 92 | with urlopen(f'http://localhost/api/settings/{quote(settingName)}') as response: 93 | return json.loads(response.read()) 94 | except Exception: 95 | logging.exception("readAPISetting %s", settingName) 96 | return '' 97 | -------------------------------------------------------------------------------- /basicPWM.py: -------------------------------------------------------------------------------- 1 | import os 2 | import logging 3 | 4 | class basicPWM: 5 | def __init__(self): 6 | self.active = False 7 | 8 | def startup(self, period=10000, dutyCycle=0): 9 | self.active = True 10 | 11 | def update(self, dutyCycle=0): 12 | pass 13 | 14 | def shutdown(self): 15 | self.active = False 16 | 17 | def status(self): 18 | # TODO: String about PWM status? 19 | pass 20 | 21 | class hardwarePWM(basicPWM): 22 | def __init__(self, pwmToUse=0): 23 | self.pwmToUse = pwmToUse 24 | if os.path.isdir('/sys/class/pwm/pwmchip0') and os.access('/sys/class/pwm/pwmchip0/export', os.W_OK): 25 | logging.info('Initializing hardware PWM%s', self.pwmToUse) 26 | else: 27 | raise RuntimeError('Unable to access /sys/class/pwm/pwmchip0') 28 | 29 | if not os.path.isdir(f'/sys/class/pwm/pwmchip0/pwm{self.pwmToUse}'): 30 | logging.debug('Exporting hardware PWM%s', pwmToUse) 31 | with open('/sys/class/pwm/pwmchip0/export', 'w', encoding='UTF-8') as p: 32 | p.write(f'{pwmToUse}\n') 33 | 34 | super().__init__() 35 | 36 | def startup(self, period=18300, dutyCycle=0): 37 | logging.debug('Starting hardware PWM%s with period of %s', self.pwmToUse, period) 38 | with open(f'/sys/class/pwm/pwmchip0/pwm{self.pwmToUse}/period', 'w', encoding='UTF-8') as p: 39 | p.write(f'{period}\n') 40 | self.update(dutyCycle) 41 | logging.info('Enabling hardware PWM%s', self.pwmToUse) 42 | with open(f'/sys/class/pwm/pwmchip0/pwm{self.pwmToUse}/enable', 'w', encoding='UTF-8') as p: 43 | p.write('1\n') 44 | super().startup() 45 | 46 | def update(self, dutyCycle=0): 47 | logging.info('Updating hardware PWM%s duty cycle to %s', self.pwmToUse, dutyCycle*61) 48 | with open(f'/sys/class/pwm/pwmchip0/pwm{self.pwmToUse}/duty_cycle', 'w', encoding='UTF-8') as p: 49 | p.write(f'{dutyCycle*61}\n') 50 | super().update() 51 | 52 | def shutdown(self): 53 | logging.debug('Shutting down hardware PWM%s', self.pwmToUse) 54 | self.update() #Duty Cycle to 0 55 | logging.info('Disabling hardware PWM%s', self.pwmToUse) 56 | with open(f'/sys/class/pwm/pwmchip0/pwm{self.pwmToUse}/enable', 'w', encoding='UTF-8') as p: 57 | p.write('0\n') 58 | super().shutdown() 59 | 60 | class softwarePWM(basicPWM): 61 | def __init__(self, pinToUse=7): 62 | logging.info('Initializing software PWM on pin %s', pinToUse) 63 | global GPIO 64 | from RPi import GPIO 65 | self.pinToUse = pinToUse 66 | self.pwm = None 67 | # TODO: Ponder if import RPi.GPIO as GPIO is a good idea 68 | GPIO.setmode(GPIO.BOARD) 69 | GPIO.setup(self.pinToUse, GPIO.OUT) 70 | GPIO.output(self.pinToUse,0) 71 | super().__init__() 72 | 73 | def startup(self, period=10000, dutyCycle=0): 74 | logging.debug('Starting software PWM on pin %s with period of %s', self.pinToUse, period) 75 | self.pwm = GPIO.PWM(self.pinToUse, period) 76 | logging.info('Updating software PWM on pin %s initial duty cycle to %s', self.pinToUse, round(dutyCycle/3,2)) 77 | self.pwm.start(dutyCycle/3) 78 | super().startup() 79 | 80 | def update(self, dutyCycle=0): 81 | logging.info('Updating software PWM on pin %s duty cycle to %s', self.pinToUse, round(dutyCycle/3,2)) 82 | self.pwm.ChangeDutyCycle(dutyCycle/3) 83 | super().update() 84 | 85 | def shutdown(self): 86 | logging.debug('Shutting down software PWM on pin %s', self.pinToUse) 87 | self.pwm.stop() 88 | logging.info('Cleaning up software PWM on pin %s', self.pinToUse) 89 | GPIO.cleanup() 90 | super().shutdown() 91 | 92 | class hardwareBBBPWM(basicPWM): 93 | def __init__(self, pwmInfo='P9_16,1,B'): 94 | (self.pinToUse, self.pwmToUse, self.ABToUse) = pwmInfo.split(',', 2) 95 | logging.info('Initializing hardware PWM on pin %s', self.pinToUse) 96 | if self.pwmToUse == '0': 97 | self.pwmToUse = '48300200' 98 | elif self.pwmToUse == '2': 99 | self.pwmToUse = '48304200' 100 | else: # Make 1 the default case 101 | self.pwmToUse = '48302200' 102 | self.ABToUse = '0' if self.ABToUse == 'A' else '1' 103 | 104 | if os.path.isfile(f'/sys/devices/platform/ocp/ocp:{self.pinToUse}_pinmux/state'): 105 | logging.info('Configuring pin %s for PWM', self.pinToUse) 106 | with open(f'/sys/devices/platform/ocp/ocp:{self.pinToUse}_pinmux/state', 'w', encoding='UTF-8') as p: 107 | p.write('pwm\n') 108 | else: 109 | raise RuntimeError(f'Unable to access /sys/devices/platform/ocp/ocp:{self.pinToUse}_pinmux/state') 110 | 111 | with os.scandir('/sys/class/pwm/') as chips: 112 | for chip in chips: 113 | if chip.is_symlink() and self.pwmToUse in os.readlink(chip): 114 | self.pwmToUse = chip.name 115 | logging.debug('PWM hardware is %s', self.pwmToUse) 116 | break 117 | 118 | if not os.path.isdir(f'/sys/class/pwm/{self.pwmToUse}/pwm{self.ABToUse}'): 119 | logging.debug('Exporting hardware %s/pwm%s', self.pwmToUse, self.ABToUse) 120 | with open(f'/sys/class/pwm/{self.pwmToUse}/export', 'w', encoding='UTF-8') as p: 121 | p.write(f'{self.ABToUse}\n') 122 | 123 | super().__init__() 124 | 125 | def startup(self, period=18300, dutyCycle=0): 126 | logging.debug('Starting hardware %s/pwm%s with period of %s', self.pwmToUse, self.ABToUse, period) 127 | with open(f'/sys/class/pwm/{self.pwmToUse}/pwm{self.ABToUse}/period', 'w', encoding='UTF-8') as p: 128 | p.write(f'{period}\n') 129 | self.update(dutyCycle) 130 | logging.info('Enabling hardware %s/pwm%s', self.pwmToUse, self.ABToUse) 131 | with open(f'/sys/class/pwm/{self.pwmToUse}/pwm{self.ABToUse}/enable', 'w', encoding='UTF-8') as p: 132 | p.write('1\n') 133 | super().startup() 134 | 135 | def update(self, dutyCycle=0): 136 | logging.info('Updating hardware %s/pwm%s duty cycle to %s', self.pwmToUse, self.ABToUse, dutyCycle*61) 137 | with open(f'/sys/class/pwm/{self.pwmToUse}/pwm{self.ABToUse}/duty_cycle', 'w', encoding='UTF-8') as p: 138 | p.write(f'{dutyCycle*61}\n') 139 | super().update() 140 | 141 | def shutdown(self): 142 | logging.debug('Shutting down hardware %s/pwm%s', self.pwmToUse, self.ABToUse) 143 | self.update() #Duty Cycle to 0 144 | logging.info('Disabling hardware %s/pwm%s', self.pwmToUse, self.ABToUse) 145 | with open(f'/sys/class/pwm/{self.pwmToUse}/pwm{self.ABToUse}/enable', 'w', encoding='UTF-8') as p: 146 | p.write('0\n') 147 | super().shutdown() 148 | -------------------------------------------------------------------------------- /callbacks.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import logging 4 | import json 5 | import os 6 | import errno 7 | import subprocess 8 | import socket 9 | import sys 10 | import time 11 | from sys import argv 12 | 13 | from config import config,read_config_from_file 14 | 15 | def logUnhandledException(eType, eValue, eTraceback): 16 | logging.error("Unhandled exception", exc_info=(eType, eValue, eTraceback)) 17 | sys.excepthook = logUnhandledException 18 | 19 | if len(argv) <= 1: 20 | print('Usage:') 21 | print(' --list | Used by FPPD at startup. Starts Dynamic_RDS_Engine.py') 22 | print(' --update | Used by Dynamic_RDS.php to apply dynamic settings to the transmitter') 23 | print(' --reset | Used by Dynamic_RDS.php to reset the GPIO pin') 24 | print(' --exit | Used by FPPD or manually to shutdown Dynamic_RDS_Engine.py') 25 | print(' --type media --data \'{..json..}\' | Used by FPPD when a new items starts in a playlist') 26 | print(' --type playlist --data \'{..json..}\' | Used by FPPD when a playlist starts or stops') 27 | print(' --type lifecycle startup/shutdown | Used by FPPD when it starts or stops') 28 | print('Note: Running with sudo might be needed for manual execution') 29 | sys.exit() 30 | 31 | script_dir = os.path.dirname(os.path.abspath(argv[0])) 32 | 33 | logging.basicConfig(filename=script_dir + '/Dynamic_RDS_callbacks.log', level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s', datefmt='%H:%M:%S') 34 | 35 | read_config_from_file() 36 | 37 | logging.getLogger().setLevel(config['DynRDSCallbackLogLevel']) 38 | 39 | logging.info('---') 40 | logging.debug('Arguments %s', argv[1:]) 41 | 42 | # If smbus is missing, don't try to start up the Engine as it will fail 43 | try: 44 | import smbus 45 | except ImportError as impErr: 46 | logging.error("Failed to import smbus %s", impErr.args[0]) 47 | sys.exit(1) 48 | 49 | # RPi.GPIO is used for software PWM on the RPi, fail if it is missing 50 | if os.getenv('FPPPLATFORM', '') == 'Raspberry Pi' and config['DynRDSTransmitter'] == "QN8066": 51 | try: 52 | import RPi.GPIO 53 | except ImportError as impErr: 54 | logging.error("Failed to import RPi.GPIO %s", impErr.args[0]) 55 | sys.exit(1) 56 | 57 | # Environ has a few useful items when FPPD runs callbacks.py, but logging it all the time, even at debug, is too much 58 | #logging.debug('Environ %s', os.environ) 59 | 60 | # Always start the Engine since it does the real work for all command 61 | updater_path = script_dir + '/Dynamic_RDS_Engine.py' 62 | engineStarted = False 63 | proc = None 64 | try: 65 | logging.debug('Checking for socket lock by %s', updater_path) 66 | lock_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) 67 | lock_socket.bind('\0Dynamic_RDS_Engine') 68 | lock_socket.close() 69 | logging.debug('Lock not found') 70 | 71 | # Short circuit if Engine isn't running and command is to shut it down 72 | if argv[1] == '--exit' or (argv[1] == '--type' and argv[2] == 'lifecycle' and argv[3] == 'shutdown'): 73 | logging.info('Exit, but not running') 74 | sys.exit() 75 | 76 | logging.info('Starting %s', updater_path) 77 | with open(os.devnull, 'w', encoding='UTF-8') as devnull: 78 | proc = subprocess.Popen(['python3', updater_path], stdin=devnull, stdout=devnull, stderr=subprocess.PIPE, close_fds=True) 79 | time.sleep(1) # Allow engine a second to start or fail before checking status 80 | engineStarted = True 81 | except socket.error: 82 | logging.debug('Lock found - %s is running', updater_path) 83 | 84 | # Always setup FIFO - Expects Engine to be running to open the read side of the FIFO 85 | fifo_path = script_dir + '/Dynamic_RDS_FIFO' 86 | try: 87 | logging.debug('Creating fifo %s', fifo_path) 88 | os.mkfifo(fifo_path) 89 | except OSError as oe: 90 | if oe.errno != errno.EEXIST: 91 | raise 92 | logging.debug('Fifo already exists') 93 | 94 | if proc is not None and proc.poll() is not None: 95 | logging.error('%s failed to stay running - %s', updater_path, proc.stderr.read().decode()) 96 | sys.exit(1) 97 | 98 | with open(fifo_path, 'w', encoding='UTF-8') as fifo: 99 | if len(argv) >= 4: 100 | logging.info('Processing %s %s %s', argv[1], argv[2], argv[3]) 101 | else: 102 | logging.info('Processing %s', argv[1]) 103 | 104 | # If Engine was started AND the argument isn't --list, INIT must be sent to Engine before the requested argument 105 | if engineStarted and argv[1] != '--list': 106 | logging.info('Engine restart detected, sending INIT') 107 | fifo.write('INIT\n') 108 | 109 | if argv[1] == '--list': 110 | # Typically called first by FPPD and will block if read side isn't open 111 | fifo.write('INIT\n') 112 | print('media,playlist,lifecycle') 113 | 114 | elif argv[1] == '--update': 115 | # Not used by FPPD, but used by Dynamic_RDS.php 116 | fifo.write('UPDATE\n') 117 | 118 | elif argv[1] == '--reset': 119 | # Not used by FPPD, but used by Dynamic_RDS.php 120 | fifo.write('RESET\n') 121 | 122 | elif argv[1] == '--exit' or (argv[1] == '--type' and argv[2] == 'lifecycle' and argv[3] == 'shutdown'): 123 | # Used by FPPD lifecycle shutdown. Also useful for testing or scripting 124 | fifo.write('EXIT\n') 125 | 126 | elif argv[1] == '--type' and argv[2] == 'media': 127 | logging.debug('Type media') 128 | try: 129 | j = json.loads(argv[4]) 130 | except Exception: 131 | logging.exception('Media JSON') 132 | 133 | # When default values are sent over fifo, other side more or less ignores them 134 | media_type = j['type'] if 'type' in j else 'pause' 135 | media_title = j['title'] if 'title' in j else '' 136 | media_artist = j['artist'] if 'artist' in j else '' 137 | media_album = j['album'] if 'album' in j else '' 138 | media_genre = j['genre'] if 'genre' in j else '' 139 | media_tracknum = str(j['track']) if 'track' in j else '0' 140 | media_length = str(j['length']) if 'length' in j else '0' 141 | 142 | logging.debug('Type is %s', media_type) 143 | logging.debug('Title is %s', media_title) 144 | logging.debug('Artist is %s', media_artist) 145 | logging.debug('Album is %s', media_album) 146 | logging.debug('Genre is %s', media_genre) 147 | logging.debug('Tracknum is %s', media_tracknum) 148 | logging.debug('Length is %s', media_length) 149 | 150 | # TODO: Other than type missing defaulting to pause, can media type be either of these any more? 151 | if media_type in ('pause', 'event'): 152 | fifo.write('T\n') # Blank Title 153 | fifo.write('A\n') # Blank Artist 154 | fifo.write('B\n') # Blank Album 155 | fifo.write('G\n') # Blank Genre 156 | else: 157 | fifo.write('T' + media_title + '\n') 158 | fifo.write('A' + media_artist + '\n') 159 | fifo.write('B' + media_album + '\n') 160 | fifo.write('G' + media_genre + '\n') 161 | fifo.write('N' + media_tracknum + '\n') 162 | fifo.write('L' + media_length + '\n') # Length is always sent last for media-based updates to optimize when the Engine has to update the RDS Data 163 | 164 | elif argv[1] == '--type' and argv[2] == 'playlist': 165 | logging.debug('Type playlist') 166 | 167 | try: 168 | j = json.loads(argv[4]) 169 | except ValueError: 170 | logging.exception('Playlist JSON') 171 | 172 | playlist_action = j['Action'] if 'Action' in j else 'stop' 173 | 174 | logging.info('Playlist action %s', j['Action']) 175 | 176 | if playlist_action == 'start': # or playlist_action == 'playing': 177 | fifo.write('START\n') 178 | elif playlist_action == 'stop': 179 | fifo.write('STOP\n') 180 | sys.exit() 181 | 182 | if j['Section'] == 'MainPlaylist': 183 | logging.debug('Playlist name %s', j['name']) 184 | fifo.write(f"MAINLIST{j['name']}\n") 185 | logging.debug('Playlist position %s', j['Item']+1) 186 | fifo.write(f"P{j['Item']+1}\n") # Playlist position is always sent last for playlist-based updates to optimize when the Engine has to update the RDS Data 187 | else: 188 | logging.debug('Clearing playlist values') 189 | fifo.write('MAINLIST\n') 190 | fifo.write('P\n') 191 | 192 | if j['currentEntry'] is None or j['currentEntry']['type'] == 'pause': 193 | # TODO: Review this case - what to send to Engine for other playlist events 194 | # Looks like a 'note' field is on all of them that could go into title 195 | logging.debug('Clearing media values') 196 | fifo.write('T\n') 197 | fifo.write('A\n') 198 | fifo.write('B\n') 199 | fifo.write('G\n') 200 | fifo.write('N\n') 201 | if j['currentEntry'] is None: 202 | fifo.write('L0\n') 203 | elif j['currentEntry']['type'] == 'pause': 204 | fifo.write(f"L{int(j['currentEntry']['duration'])}\n") 205 | logging.debug('Processing done') 206 | -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 1 | import os 2 | import logging 3 | 4 | config = { 5 | 'DynRDSEnableRDS': '1', 6 | 'DynRDSPSUpdateRate': '4', 7 | 'DynRDSPSStyle': 'Merry|Christ-| -mas!|{T}|{A}|[{N} of {C}]', 8 | 'DynRDSRTUpdateRate': '8', 9 | 'DynRDSRTSize': '32', 10 | 'DynRDSRTStyle': 'Merry Christmas!|{T}[ by {A}]|[Track {N} of {C}]', 11 | 'DynRDSPty': '2', 12 | 'DynRDSPICode': '819b', 13 | 'DynRDSTransmitter': 'None', 14 | 'DynRDSFrequency': '100.1', 15 | 'DynRDSPreemphasis': '75us', 16 | 'DynRDSQN8066Gain': '0', 17 | 'DynRDSQN8066SoftClipping': '0', 18 | 'DynRDSQN8066AGC': '0', 19 | 'DynRDSQN8066ChipPower': '122', 20 | 'DynRDSQN8066PIPWM': 0, 21 | 'DynRDSQN8066AmpPower': '0', 22 | 'DynRDSStart': 'FPPDStart', 23 | 'DynRDSStop': 'Never', 24 | 'DynRDSCallbackLogLevel': 'INFO', 25 | 'DynRDSEngineLogLevel': 'INFO', 26 | 'DynRDSmpcEnable': '0', 27 | 'DynRDSAdvPISoftwareI2C': '0', 28 | 'DynRDSAdvPIPWMPin': '18,2', 29 | 'DynRDSAdvBBBPWMPin': 'P9_16,1,B', 30 | 'DynRDSmqttEnable': '0' 31 | } 32 | 33 | def read_config_from_file(): 34 | configfile = os.getenv('CFGDIR', '/home/fpp/media/config') + '/plugin.Dynamic_RDS' 35 | try: 36 | with open(configfile, 'r', encoding='UTF-8') as f: 37 | for confline in f: 38 | (confkey, confval) = confline.split(' = ') 39 | config[confkey] = confval.replace('"', '').strip() 40 | except IOError: 41 | logging.warning('No config file found, using defaults.') 42 | except Exception: 43 | logging.exception('read_config') 44 | -------------------------------------------------------------------------------- /images/README.md: -------------------------------------------------------------------------------- 1 | Images for the plugin and related documentation 2 | -------------------------------------------------------------------------------- /images/RPi_to_QN8066_cable.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShadowLight8/Dynamic_RDS/c1c42d6abd32d2e3a91da644b5a4978d04a500c5/images/RPi_to_QN8066_cable.jpeg -------------------------------------------------------------------------------- /images/pi_transmitter_setup1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShadowLight8/Dynamic_RDS/c1c42d6abd32d2e3a91da644b5a4978d04a500c5/images/pi_transmitter_setup1.jpg -------------------------------------------------------------------------------- /images/pi_transmitter_setup2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShadowLight8/Dynamic_RDS/c1c42d6abd32d2e3a91da644b5a4978d04a500c5/images/pi_transmitter_setup2.jpg -------------------------------------------------------------------------------- /images/pi_transmitter_setup3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShadowLight8/Dynamic_RDS/c1c42d6abd32d2e3a91da644b5a4978d04a500c5/images/pi_transmitter_setup3.jpg -------------------------------------------------------------------------------- /images/radio_board.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShadowLight8/Dynamic_RDS/c1c42d6abd32d2e3a91da644b5a4978d04a500c5/images/radio_board.jpeg -------------------------------------------------------------------------------- /images/radio_board_and_pi_pinout.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShadowLight8/Dynamic_RDS/c1c42d6abd32d2e3a91da644b5a4978d04a500c5/images/radio_board_and_pi_pinout.jpeg -------------------------------------------------------------------------------- /images/radio_board_pinout.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShadowLight8/Dynamic_RDS/c1c42d6abd32d2e3a91da644b5a4978d04a500c5/images/radio_board_pinout.jpeg -------------------------------------------------------------------------------- /images/radio_board_w_screen.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShadowLight8/Dynamic_RDS/c1c42d6abd32d2e3a91da644b5a4978d04a500c5/images/radio_board_w_screen.jpeg -------------------------------------------------------------------------------- /images/raspberry_pi_connection.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShadowLight8/Dynamic_RDS/c1c42d6abd32d2e3a91da644b5a4978d04a500c5/images/raspberry_pi_connection.jpeg -------------------------------------------------------------------------------- /menu.inc: -------------------------------------------------------------------------------- 1 | 'Dynamic RDS', 17 | 'type' => 'status', 18 | 'page' => 'Dynamic_RDS.php', 19 | 'wrap' => 1 20 | ) 21 | ); 22 | 23 | ############################################################################## 24 | # Display the menu entries for this plugin. 25 | # 26 | # It is expected that two variables are alread set: 27 | # $plugin - contains the name of the current plugin directory/repoName 28 | # $menu - contains the name of the menu section/type 29 | foreach ($menuEntries as $entry) 30 | { 31 | if ($entry['type'] != $menu) 32 | continue; 33 | 34 | if (preg_match('/^http.?:\/\//', $entry['page'])) 35 | { 36 | printf("
  • %s
  • \n", 37 | $entry['page'], $entry['text']); 38 | } 39 | else 40 | { 41 | $nopage = ''; 42 | if (isset($entry['wrap']) && ($entry['wrap'] == 0)) 43 | $nopage = '&nopage=1'; 44 | 45 | printf("
  • %s
  • \n", 46 | $plugin, $entry['page'], $nopage, $entry['text']); 47 | } 48 | } 49 | ?> 50 | -------------------------------------------------------------------------------- /pluginInfo.json: -------------------------------------------------------------------------------- 1 | { 2 | "repoName": "Dynamic_RDS", 3 | "name": "Dynamic RDS", 4 | "author": "Nick Anderson (ShadowLight8)", 5 | "description": "Manage an FM Transmitter and generate customizable RDS messages similar to typical FM stations. Reads multiple fields from the media's metadata and playlist. Run on Raspberry Pi and BBB. Supports the QN8066 chip.", 6 | 7 | "homeURL": "https://github.com/ShadowLight8/Dynamic_RDS", 8 | "srcURL": "https://github.com/ShadowLight8/Dynamic_RDS.git", 9 | "bugURL": "https://github.com/ShadowLight8/Dynamic_RDS/issues", 10 | "versions": [ 11 | { 12 | "minFPPVersion": "6.0", 13 | "maxFPPVersion": "7.2", 14 | "branch": "main", 15 | "sha": "d06b4e623afc1f083036277c248012e4f8f29d38", 16 | "platforms": [ 17 | "Raspberry Pi" 18 | ] 19 | }, 20 | { 21 | "minFPPVersion": "7.3", 22 | "maxFPPVersion": "7.99", 23 | "branch": "main", 24 | "sha": "5dfa0bf88e5b948c0cf130e4a8b6363f7d5b6126", 25 | "allowUpdates": 1 26 | }, 27 | { 28 | "minFPPVersion": "8.0", 29 | "maxFPPVersion": "0", 30 | "branch": "main", 31 | "sha": "", 32 | "allowUpdates": 1 33 | } 34 | ] 35 | } 36 | -------------------------------------------------------------------------------- /scripts/fpp_install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo "Copying, if missing, optional config script to FPP scripts directory..." 4 | cp -v -n ~/media/plugins/Dynamic_RDS/scripts/src_Dynamic_RDS_config.sh ~/media/scripts/Dynamic_RDS_config.sh 5 | 6 | echo -e "\nInstalling python3-smbus..." 7 | sudo apt-get install -y python3-smbus 8 | 9 | if test -f /boot/config.txt; then 10 | echo -e "\nInstalling RPi.GPIO..." 11 | sudo apt-get install -y python3-rpi.gpio 12 | fi 13 | 14 | echo -e "\nRestarting FPP..." 15 | curl -s http://localhost/api/system/fppd/restart 16 | -------------------------------------------------------------------------------- /scripts/fpp_uninstall.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo "Stopping Dynamic RDS engine..." 4 | sudo /home/fpp/media/plugins/Dynamic_RDS/callbacks.py --exit 5 | 6 | if cmp -s ~/media/plugins/Dynamic_RDS/scripts/src_Dynamic_RDS_config.sh ~/media/scripts/Dynamic_RDS_config.sh; then 7 | echo -e "\nRemoving optional config script from FPP scripts directory..." 8 | rm ~/media/scripts/Dynamic_RDS_config.sh 9 | else 10 | echo -e "\nLeaving modified optional config script" 11 | fi 12 | 13 | echo -e "\nYou can manually uninstall python3-smbus if nothing else uses it." 14 | echo "Command is: sudo apt-get remove -y python3-smbus" 15 | -------------------------------------------------------------------------------- /scripts/paho_install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo -e "\nInstalling python3-paho-mqtt..." 4 | sudo apt-get install -y python3-paho-mqtt 5 | 6 | -------------------------------------------------------------------------------- /scripts/src_Dynamic_RDS_config.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | ############################################################################### 3 | # Dynamic_RDS_config.sh - Used to change the PS and/or RT RDS Strings # 4 | ############################################################################### 5 | 6 | # Set the PS text (set to '' or comment out to leave unchanged) 7 | PS='Merry|Christ-| -mas!|{T}|{A}|[{N} of {C}]' 8 | 9 | # Set the RT text (set to '' or comment out to leave unchanged) 10 | RT='Merry Christmas! {T}[ by {A}]|[Track {N} of {C}]' 11 | 12 | if [ "$PS" != "" ]; then 13 | echo 'Setting PS Style Text to: '$PS 14 | curl -d "$PS" -X POST http://localhost/api/plugin/Dynamic_RDS/settings/DynRDSPSStyle 15 | echo -e '\n' 16 | fi 17 | 18 | if [ "$RT" != "" ]; then 19 | echo 'Setting RT Style Text to: '$RT 20 | curl -d "$RT" -X POST http://localhost/api/plugin/Dynamic_RDS/settings/DynRDSRTStyle 21 | echo -e '\n' 22 | fi 23 | 24 | echo 'Applying changes' 25 | 26 | curl http://localhost/api/plugin/Dynamic_RDS/FastUpdate 27 | 28 | echo 'Complete' 29 | -------------------------------------------------------------------------------- /settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "settingGroups": { 3 | "DynRDSRDSSettings": { 4 | "description": "RDS Settings", 5 | "settings": [ 6 | "DynRDSEnableRDS", 7 | "DynRDSPSUpdateRate", 8 | "DynRDSPSStyle", 9 | "DynRDSRTUpdateRate", 10 | "DynRDSRTSize", 11 | "DynRDSRTStyle", 12 | "DynRDSPty", 13 | "DynRDSPICode" 14 | ] 15 | }, 16 | "DynRDSTransmitterSettings": { 17 | "description": "Transmitter Type and Common Settings", 18 | "settings": [ 19 | "DynRDSTransmitter", 20 | "DynRDSFrequency", 21 | "DynRDSPreemphasis" 22 | ] 23 | }, 24 | "DynRDSAudioSettings": { 25 | "description": "Audio Settings", 26 | "settings": [ 27 | "DynRDSQN8066Gain", 28 | "DynRDSQN8066SoftClipping", 29 | "DynRDSQN8066AGC", 30 | "DynRDSSi4713TestAudio" 31 | ] 32 | }, 33 | "DynRDSPowerSettings": { 34 | "description": "Power Settings", 35 | "settings": [ 36 | "DynRDSQN8066ChipPower", 37 | "DynRDSQN8066PIPWM", 38 | "DynRDSQN8066AmpPower" 39 | ] 40 | }, 41 | "DynRDSPluginActivation": { 42 | "description": "Plugin Activation", 43 | "settings": [ 44 | "DynRDSStart", 45 | "DynRDSStop" 46 | ] 47 | }, 48 | "DynRDSLogLevel": { 49 | "description": "Log Levels", 50 | "settings": [ 51 | "DynRDSCallbackLogLevel", 52 | "DynRDSEngineLogLevel" 53 | ] 54 | }, 55 | "DynRDSmpc": { 56 | "description": "MPC / After Hours Music", 57 | "settings": [ 58 | "DynRDSmpcEnable" 59 | ] 60 | }, 61 | "DynRDSmqtt": { 62 | "description": "MQTT", 63 | "settings": [ 64 | "DynRDSmqttEnable" 65 | ] 66 | }, 67 | "DynRDSAdv": { 68 | "description": "Advanced Options", 69 | "settings": [ 70 | "DynRDSAdvPISoftwareI2C", 71 | "DynRDSAdvPIPWMPin", 72 | "DynRDSAdvBBBPWMPin" 73 | ] 74 | } 75 | }, 76 | "settings": { 77 | "DynRDSTransmitter": { 78 | "name": "DynRDSTransmitter", 79 | "description": "Transmitter Type (Auto-Selected)", 80 | "tip": "When not set, will be set based on I2C detection. Can be changed manually.", 81 | "restart": 1, 82 | "reboot": 0, 83 | "type": "select", 84 | "options": { 85 | "SELECT TRANSMITTER": "None", 86 | "QN8066": "QN8066", 87 | "Si4713 (planned for future release)": "zzSi4713" 88 | }, 89 | "default": "None", 90 | "children": { 91 | "QN8066": [ 92 | "DynRDSQN8066Gain", 93 | "DynRDSQN8066SoftClipping", 94 | "DynRDSQN8066AGC", 95 | "DynRDSQN8066ChipPower", 96 | "DynRDSQN8066PIPWM", 97 | "DynRDSQN8066AmpPower" 98 | ], 99 | "Si4713": [ 100 | "DynRDSSi4713TestAudio" 101 | ] 102 | } 103 | }, 104 | "DynRDSStart": { 105 | "name": "DynRDSStart", 106 | "description": "Start with", 107 | "tip": "When starting, the transmitter is reset, settings initialized, will broadcast any audio played, and send static RDS messages (if enabled).", 108 | "restart": 1, 109 | "reboot": 0, 110 | "type": "select", 111 | "options": { 112 | "FPPD Start (default)": "FPPDStart", 113 | "Playlist Start": "PlaylistStart", 114 | "Never": "Never" 115 | }, 116 | "default": "FPPDStart" 117 | }, 118 | "DynRDSStop": { 119 | "name": "DynRDSStop", 120 | "description": "Stop with", 121 | "tip": "When stopped, the transmitter is reset. Listeners will hear static.", 122 | "restart": 1, 123 | "reboot": 0, 124 | "type": "select", 125 | "options": { 126 | "Playlist Stop": "PlaylistStop", 127 | "Never (default)": "Never" 128 | }, 129 | "default": "Never" 130 | }, 131 | "DynRDSQN8066ChipPower": { 132 | "name": "DynRDSQN8066ChipPower", 133 | "description": "Chip Power (92-122)", 134 | "tip": "Adjust the power output from the transmitter chip", 135 | "restart": 1, 136 | "reboot": 0, 137 | "type": "number", 138 | "min": 92, 139 | "max": 122, 140 | "step": 1, 141 | "suffix": "dBμV", 142 | "default": 122 143 | }, 144 | "DynRDSQN8066PIPWM": { 145 | "name": "DynRDSQN8066PIPWM", 146 | "description": "Enable PWM", 147 | "tip": "Enables Raspberry Pi hardware-based PWM on Pin 12 / GPIO 18 by default. Used to control the Amp Power. This requires the on-board audio to be disabled as it also used the PWM hardware, so an external sound card is required.", 148 | "suffix": "- Disables on-board audio, external sound card required", 149 | "restart": 0, 150 | "reboot": 1, 151 | "type": "checkbox", 152 | "checkedValue": "1", 153 | "uncheckedValue": "0", 154 | "default": 0, 155 | "children": { 156 | "1": [ 157 | "DynRDSQN8066AmpPower", 158 | "DynRDSAdvPIPWMPin" 159 | ] 160 | }, 161 | "platforms": [ 162 | "Raspberry Pi" 163 | ] 164 | }, 165 | "DynRDSQN8066AmpPower": { 166 | "name": "DynRDSQN8066AmpPower", 167 | "description": "Amp Power (0-100)", 168 | "tip": "Adjust the power output for the amplifier after the transmitter chip. This is controlled by PWM output.", 169 | "suffix": " - Controlled by PWM", 170 | "restart": 0, 171 | "reboot": 0, 172 | "type": "number", 173 | "min": 0, 174 | "max": 100, 175 | "step": 1, 176 | "default": 0 177 | }, 178 | "DynRDSFrequency": { 179 | "name": "DynRDSFrequency", 180 | "description": "Frequency (60.00-108.00)", 181 | "tip": "Broadcast frequency of the transmitter", 182 | "restart": 1, 183 | "reboot": 0, 184 | "type": "number", 185 | "min": 60.00, 186 | "max": 108.00, 187 | "step": 0.05, 188 | "suffix": "MHz", 189 | "default": 100.10 190 | }, 191 | "DynRDSPreemphasis": { 192 | "name": "DynRDSPreemphasis", 193 | "description": "Preemphasis", 194 | "tip": "Used in FM broadcast to improve quality of higher frequencies. Most of the world uses 50μs, except the US and South Korea at 75μs", 195 | "restart": 1, 196 | "reboot": 0, 197 | "type": "select", 198 | "options": { 199 | "75 μs (USA, default)": "75us", 200 | "50 μs (Europe, Australia, Japan)": "50us" 201 | }, 202 | "default": "75us" 203 | }, 204 | "DynRDSQN8066Gain": { 205 | "name": "DynRDSQN8066Gain", 206 | "description": "Gain Adjustment (-15 to +20)", 207 | "tip": "Adjust volume of broadcast audio. In testing, if this is too high or low the audio will be distorted, cut out randomly, or no audio will be heard.", 208 | "restart": 0, 209 | "reboot": 0, 210 | "type": "number", 211 | "min": -15, 212 | "max": 20, 213 | "step": 1, 214 | "default": 0, 215 | "suffix": "" 216 | }, 217 | "DynRDSQN8066SoftClipping": { 218 | "name": "DynRDSQN8066SoftClipping", 219 | "description": "Enable Soft Clipping", 220 | "restart": 0, 221 | "reboot": 0, 222 | "type": "checkbox", 223 | "checkedValue": "1", 224 | "uncheckedValue": "0", 225 | "default": 1, 226 | "suffix": "" 227 | }, 228 | "DynRDSQN8066AGC": { 229 | "name": "DynRDSQN8066AGC", 230 | "description": "Enable AGC (not recommended)", 231 | "restart": 0, 232 | "reboot": 0, 233 | "type": "checkbox", 234 | "checkedValue": "1", 235 | "uncheckedValue": "0", 236 | "default": 0, 237 | "suffix": "" 238 | }, 239 | "DynRDSSi4713TestAudio": { 240 | "name": "DynRDSSi4713TestAudio", 241 | "description": "Test Si4713 Setting", 242 | "type": "text" 243 | }, 244 | "DynRDSEnableRDS": { 245 | "name": "DynRDSEnableRDS", 246 | "description": "Enable RDS", 247 | "restart": 1, 248 | "reboot": 0, 249 | "type": "checkbox", 250 | "checkedValue": "1", 251 | "uncheckedValue": "0", 252 | "default": 1, 253 | "children": { 254 | "1": [ 255 | "DynRDSPICode", 256 | "DynRDSPty", 257 | "DynRDSPSUpdateRate", 258 | "DynRDSPSStyle", 259 | "DynRDSRTUpdateRate", 260 | "DynRDSRTSize", 261 | "DynRDSRTStyle" 262 | ] 263 | } 264 | }, 265 | "DynRDSPSStyle": { 266 | "name": "DynRDSPSStyle", 267 | "description": "PS Style Text (8 chars per update)", 268 | "tip": "Sent 8 characters at a time. Program Service is the most commonly displayed part of RDS.", 269 | "restart": 1, 270 | "reboot": 0, 271 | "type": "text", 272 | "size": 32, 273 | "maxlength": 64, 274 | "default": "Merry|Christ-| -mas!|{T}|{A}|[{N} of {C}]" 275 | }, 276 | "DynRDSPSUpdateRate": { 277 | "name": "DynRDSPSUpdateRate", 278 | "description": "PS Update Rate", 279 | "tip": "Interval between updating the 8 characters being sent. It takes ~1 second to send the 8 characters and some radios only display the text after receiving the full group twice.", 280 | "suffix": "seconds", 281 | "restart": 1, 282 | "reboot": 0, 283 | "type": "number", 284 | "min": 3, 285 | "max": 60, 286 | "step": 1, 287 | "default": 4 288 | }, 289 | "DynRDSRTStyle": { 290 | "name": "DynRDSRTStyle", 291 | "description": "RT Style Text", 292 | "tip": "Sent up to 64 characters at a time. Radio Text is intended for longer message with a slower update rate.", 293 | "restart": 1, 294 | "reboot": 0, 295 | "type": "text", 296 | "size": 64, 297 | "maxlength": 256, 298 | "default": "Merry Christmas!|{T}[ by {A}]|[Track {N} of {C}]" 299 | }, 300 | "DynRDSRTUpdateRate": { 301 | "name": "DynRDSRTUpdateRate", 302 | "description": "RT Update Rate", 303 | "tip": "Interval between updating the 64 characters being sent. It takes ~4 seconds to send the 64 characters and some radios only display the text after receiving the full group twice.", 304 | "suffix": "seconds", 305 | "restart": 1, 306 | "reboot": 0, 307 | "type": "number", 308 | "min": 3, 309 | "max": 60, 310 | "step": 1, 311 | "default": 8 312 | }, 313 | "DynRDSRTSize": { 314 | "name": "DynRDSRTSize", 315 | "description": "RT Update Size", 316 | "tip": "While RadioText (RT) can be up to 64 characters at a time, not all radios will display everything at the same time. A smaller setting is recommended.", 317 | "restart": 1, 318 | "reboot": 0, 319 | "type": "number", 320 | "min": 8, 321 | "max": 64, 322 | "step": 1, 323 | "default": 32, 324 | "suffix": "characters" 325 | }, 326 | "DynRDSPty": { 327 | "name": "DynRDSPty", 328 | "description": "Program Type", 329 | "tip": "Predefined Program Types with different assignments between North America and Europe", 330 | "restart": 1, 331 | "reboot": 0, 332 | "type": "select", 333 | "options": { 334 | "0 - None / None": 0, 335 | "1 - News / News": 1, 336 | "2 - Information / Current Affairs": 2, 337 | "3 - Sport / Information": 3, 338 | "4 - Talk / Sport": 4, 339 | "5 - Rock / Education": 5, 340 | "6 - Classic Rock / Drama": 6, 341 | "7 - Adult Hits / Culture": 7, 342 | "8 - Soft Rock / Science": 8, 343 | "9 - Top 40 / Varied": 9, 344 | "10 - Country / Pop": 10, 345 | "11 - Oldies / Rock": 11, 346 | "12 - Soft Music / Easy Listening": 12, 347 | "13 - Nostalgia / Light Classical": 13, 348 | "14 - Jazz / Serious Classical": 14, 349 | "15 - Classical / Other Music": 15, 350 | "16 - R&B / Weather": 16, 351 | "17 - Soft R&B / Finance": 17, 352 | "18 - Language / Childrens": 18, 353 | "19 - Religious Music / Social Affairs": 19, 354 | "20 - Religious Talk / Religion": 20, 355 | "21 - Personality / Phone-In": 21, 356 | "22 - Public / Travel": 22, 357 | "23 - College / Leisure": 23, 358 | "24 - Spanish Talk / Jazz": 24, 359 | "25 - Spanish Music / Country": 25, 360 | "26 - Hip Hop / National Music": 26, 361 | "27 - --- / Oldies": 27, 362 | "28 - --- / Folk": 28, 363 | "29 - Weather / Documentary": 29 364 | }, 365 | "default": 2, 366 | "suffix": "North America / Europe" 367 | }, 368 | "DynRDSPICode": { 369 | "name": "DynRDSPICode", 370 | "description": "PI Code", 371 | "tip": "Unique program indentification code. While no longer the standard in the US, some older recievers will attempt to translate the PI code to a callsign. Can use 819b for WRAP or 5F64 for WEBS. You can search at https://picodes.nrscstandards.org for unused codes or calculate your own at https://caseymediallc.com/rdsreverse. First character of callsign is limited to W or K.", 372 | "restart": 1, 373 | "reboot": 0, 374 | "type": "text", 375 | "size": 4, 376 | "maxlength": 4, 377 | "default": "819b" 378 | }, 379 | "DynRDSCallbackLogLevel": { 380 | "name": "DynRDSCallbackLogLevel", 381 | "description": "Logging Level for Callback", 382 | "restart": 0, 383 | "reboot": 0, 384 | "type": "select", 385 | "options": { 386 | "Errors Only": "ERROR", 387 | "Warn": "WARNING", 388 | "Info": "INFO", 389 | "Debug": "DEBUG" 390 | }, 391 | "default": "INFO" 392 | }, 393 | "DynRDSEngineLogLevel": { 394 | "name": "DynRDSEngineLogLevel", 395 | "description": "Logging Level for Engine", 396 | "restart": 0, 397 | "reboot": 0, 398 | "type": "select", 399 | "options": { 400 | "Errors Only": "ERROR", 401 | "Warn": "WARNING", 402 | "Info": "INFO", 403 | "Debug": "DEBUG", 404 | "Excessive": "EXCESSIVE" 405 | }, 406 | "default": "INFO" 407 | }, 408 | "DynRDSmpcEnable": { 409 | "name": "DynRDSmpcEnable", 410 | "description": "Enable MPC support", 411 | "tip": "Pulls %title% from mpc and displays it as {T} in the RDS Style Text", 412 | "restart": 0, 413 | "reboot": 0, 414 | "type": "checkbox", 415 | "checkedValue": "1", 416 | "uncheckedValue": "0", 417 | "default": 0, 418 | "suffix": "" 419 | }, 420 | "DynRDSmqttEnable": { 421 | "name": "DynRDSmqttEnable", 422 | "description": "Enable MQTT", 423 | "tip": "Enables Dynamic_RDS to publish status to MQTT", 424 | "restart": 0, 425 | "reboot": 0, 426 | "type": "checkbox", 427 | "checkedValue": "1", 428 | "uncheckedValue": "0", 429 | "default": 0, 430 | "suffix": "" 431 | }, 432 | "DynRDSAdvPISoftwareI2C": { 433 | "name": "DynRDSAdvPISoftwareI2C", 434 | "description": "Use PI Software I2C", 435 | "tip": "Switches PI from hardware I2C to software I2C in /boot/config.txt", 436 | "restart": 0, 437 | "reboot": 1, 438 | "type": "checkbox", 439 | "checkedValue": "1", 440 | "uncheckedValue": "0", 441 | "default": 0, 442 | "platforms": [ 443 | "Raspberry Pi" 444 | ] 445 | }, 446 | "DynRDSAdvPIPWMPin": { 447 | "name": "DynRDSAdvPIPWMPin", 448 | "description": "PI PWM Pin", 449 | "tip": "Select which Pin/GPIO has the PWM output. PWM0/1 are for true hareware-generated PWM, but is limited to specific pins. This uses the PWM hardware, so on-board audio is still disabled and an external sound card is needed.", 450 | "restart": 0, 451 | "reboot": 1, 452 | "type": "select", 453 | "options": { 454 | "PWM0 - Pin 12 / GPIO 18 (default)": "18,2", 455 | "PWM0 - Pin 32 / GPIO 12": "12,4", 456 | "PWM1 - Pin 33 / GPIO 13": "13,4", 457 | "PWM1 - Pin 35 / GPIO 19": "19,2", 458 | "Software - Pin 7 / GPIO 4": "7", 459 | "Software - Pin 8 / GPIO 14": "8", 460 | "Software - Pin 10 / GPIO 15": "10", 461 | "Software - Pin 11 / GPIO 17": "11", 462 | "Software - Pin 13 / GPIO 27": "13", 463 | "Software - Pin 15 / GPIO 22": "15", 464 | "Software - Pin 16 / GPIO 23": "16", 465 | "Software - Pin 18 / GPIO 24": "18", 466 | "Software - Pin 22 / GPIO 25": "22", 467 | "Software - Pin 27 / GPIO 0": "27", 468 | "Software - Pin 28 / GPIO 1": "28", 469 | "Software - Pin 29 / GPIO 5": "29", 470 | "Software - Pin 31 / GPIO 6": "31", 471 | "Software - Pin 36 / GPIO 16": "36", 472 | "Software - Pin 37 / GPIO 26": "37" 473 | }, 474 | "default": "18,2", 475 | "platforms": [ 476 | "Raspberry Pi" 477 | ] 478 | }, 479 | "DynRDSAdvBBBPWMPin": { 480 | "name": "DynRDSAdvBBBPWMPin", 481 | "description": "BBB PWM Pin", 482 | "tip": "Select which Pin has the PWM output.", 483 | "restart": 1, 484 | "reboot": 0, 485 | "type": "select", 486 | "options": { 487 | "PWM0A - Pin P9_22": "P9_22,0,A", 488 | "PWM0A - Pin P9_31": "P9_31,0,A", 489 | "PWM0B - Pin P9_21": "P9_21,0,B", 490 | "PWM0B - Pin P9_29": "P9_29,0,B", 491 | "PWM1A - Pin P9_14": "P9_14,1,A", 492 | "PWM1A - Pin P8_36": "P8_36,1,A", 493 | "PWM1B - Pin P9_16 (default)": "P9_16,1,B", 494 | "PWM1B - Pin P8_34": "P8_34,1,B", 495 | "PWM2A - Pin P8_19": "P8_19,2,A", 496 | "PWM2A - Pin P8_45": "P8_45,2,A", 497 | "PWM2B - Pin P8_13": "P8_13,2,B", 498 | "PWM2B - Pin P8_46": "P8_46,2,B" 499 | }, 500 | "default": "P9_16,1,B", 501 | "platforms": [ 502 | "BeagleBone Black" 503 | ] 504 | } 505 | } 506 | } 507 | --------------------------------------------------------------------------------