file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
OnpcSocket.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/OnpcSocket.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp; import android.content.Context; import android.widget.Toast; import com.mkulesh.onpc.R; import com.mkulesh.onpc.utils.Logging; import com.mkulesh.onpc.utils.Utils; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.util.Calendar; import androidx.annotation.NonNull; public class OnpcSocket implements ConnectionIf { private final static long CONNECTION_TIMEOUT = 5000; private final static int SOCKET_BUFFER = 4 * 1024; // connected host (ConnectionIf) private String host = ConnectionIf.EMPTY_HOST; private int port = ConnectionIf.EMPTY_PORT; // Socket handling private SocketChannel socket = null; // data handling private byte[] packetJoinBuffer = null; private final ByteBuffer rawBuffer = ByteBuffer.allocate(SOCKET_BUFFER); interface DataListener { void onData(ByteBuffer buffer); } @NonNull @Override public String getHost() { return host; } @Override public int getPort() { return port; } @NonNull @Override public String getHostAndPort() { return Utils.ipToString(host, port); } public SocketChannel getSocket() { return socket; } public boolean open(String host, int port, final Context context, boolean showInfo) { this.host = host; this.port = port; try { socket = SocketChannel.open(); socket.configureBlocking(false); socket.connect(new InetSocketAddress(host, port)); final long startTime = Calendar.getInstance().getTimeInMillis(); while (!socket.finishConnect()) { final long currTime = Calendar.getInstance().getTimeInMillis(); if (currTime > startTime + CONNECTION_TIMEOUT) { throw new Exception("connection timeout"); } } if (socket.socket().getInetAddress() != null && socket.socket().getInetAddress().getHostAddress() != null) { this.host = socket.socket().getInetAddress().getHostAddress(); } Logging.info(this, "connected to " + getHostAndPort()); return true; } catch (Exception e) { String message = String.format(context.getResources().getString( R.string.error_connection_no_response), getHostAndPort()); Logging.info(this, message + ": " + e.getLocalizedMessage()); if (showInfo) { for (StackTraceElement t : e.getStackTrace()) { Logging.info(this, t.toString()); } } try { // An exception is possible here: // Can't toast on a thread that has not called Looper.prepare() if (showInfo) { Toast.makeText(context, message, Toast.LENGTH_LONG).show(); } } catch (Exception e1) { // nothing to do } } socket = null; return false; } public void close() throws IOException { if (socket != null) { socket.close(); } } public int readData(@NonNull DataListener dataListener) throws IOException { rawBuffer.clear(); final int readSize = socket.read(rawBuffer); if (readSize < 0) { Logging.info(this, "host " + getHostAndPort() + " disconnected"); return readSize; } else if (readSize > 0) { try { dataListener.onData(rawBuffer); } catch (Exception e) { Logging.info(this, "error: process input data: " + e.getLocalizedMessage()); return -1; } } return readSize; } public byte[] joinBuffer(ByteBuffer buffer) { buffer.flip(); final int incoming = buffer.remaining(); byte[] bytes; if (packetJoinBuffer == null) { // A new buffer - just copy it bytes = new byte[incoming]; buffer.get(bytes); } else { // Remaining part of existing buffer - join it final int s1 = packetJoinBuffer.length; bytes = new byte[s1 + incoming]; System.arraycopy(packetJoinBuffer, 0, bytes, 0, s1); buffer.get(bytes, s1, incoming); packetJoinBuffer = null; } return bytes; } public void setBuffer(byte[] bytes) { packetJoinBuffer = bytes; } }
5,599
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
MessageChannelDcp.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/MessageChannelDcp.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp; import android.os.StrictMode; import com.jayway.jsonpath.JsonPath; import com.mkulesh.onpc.iscp.messages.DCPMessageFactory; import com.mkulesh.onpc.iscp.messages.DcpReceiverInformationMsg; import com.mkulesh.onpc.iscp.messages.OperationCommandMsg; import com.mkulesh.onpc.iscp.messages.TimeInfoMsg; import com.mkulesh.onpc.utils.AppTask; import com.mkulesh.onpc.utils.Logging; import com.mkulesh.onpc.utils.Utils; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Calendar; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import androidx.annotation.NonNull; public class MessageChannelDcp extends AppTask implements Runnable, MessageChannel { private final static String DCP_FORM_IPHONE_APP = "formiPhoneApp"; private final static String DCP_APP_COMMAND = "<cmd id=\"1\">"; private final static String DCP_HEOS_REQUEST = "heos://"; public final static String DCP_HEOS_RESPONSE = "{\"heos\":"; private final static int CR = 0x0D; private final static int LF = 0x0A; // thread implementation private final AtomicBoolean threadCancelled = new AtomicBoolean(); // connection state private final ConnectionState connectionState; private final OnpcSocket dcpSocket = new OnpcSocket(); private final OnpcSocket heosSocket = new OnpcSocket(); // HEOS connection is optional // input-output queues private final BlockingQueue<EISCPMessage> outputQueue = new ArrayBlockingQueue<>(QUEUE_SIZE, true); private final BlockingQueue<ISCPMessage> inputQueue; // message handling private final DCPMessageFactory dcpMessageFactory = new DCPMessageFactory(); private Integer heosPid = null; MessageChannelDcp(final int zone, final ConnectionState connectionState, final BlockingQueue<ISCPMessage> inputQueue) { super(false); this.connectionState = connectionState; this.inputQueue = inputQueue; StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); dcpMessageFactory.prepare(zone); } public void start() { if (isActive()) { return; } super.start(); final Thread thread = new Thread(this, this.getClass().getSimpleName()); threadCancelled.set(false); thread.start(); } public void stop() { synchronized (threadCancelled) { threadCancelled.set(true); } } @NonNull @Override public String getHost() { return dcpSocket.getHost(); } @Override public int getPort() { return dcpSocket.getPort(); } @NonNull @Override public String getHostAndPort() { return dcpSocket.getHostAndPort(); } @Override public void addAllowedMessage(final String code) { // nothing to do } @Override public ProtoType getProtoType() { return ConnectionIf.ProtoType.DCP; } @Override public void run() { Logging.info(this, "started " + getHostAndPort() + ":" + this); // Output data processing Long lastSendTime = null; final long DCP_SEND_DELAY = 75; // Send the COMMAND in 50ms or more intervals. final ArrayList<String> dcpOutputBuffer = new ArrayList<>(); while (true) { try { synchronized (threadCancelled) { if (threadCancelled.get()) { Logging.info(this, "cancelled " + getHostAndPort()); break; } } if (!connectionState.isNetwork()) { Logging.info(this, "no network"); break; } // process DCP input messages if (dcpSocket.readData((ByteBuffer b) -> processInputData(b, dcpSocket)) < 0) { break; } // process HEOS input messages if (heosSocket.getSocket() != null) { if (heosSocket.readData((ByteBuffer b) -> processInputData(b, heosSocket)) < 0) { break; } } // process output messages // DCP documentation: Send the COMMAND in 50ms or more intervals. long currTime = Calendar.getInstance().getTimeInMillis(); if (lastSendTime == null || currTime - lastSendTime >= DCP_SEND_DELAY) { if (!dcpOutputBuffer.isEmpty()) { final String rawCmd = dcpOutputBuffer.remove(0); if (rawCmd.startsWith(DCP_FORM_IPHONE_APP)) { sendDcpFormIphoneApp(rawCmd); } else if (rawCmd.startsWith(DCP_APP_COMMAND)) { sendDcpAppCommand(rawCmd); } else if (rawCmd.startsWith(DCP_HEOS_REQUEST)) { sendDcpHeosRequest(rawCmd); } else { sendDcpRawMsg(rawCmd); } lastSendTime = currTime; } else { final EISCPMessage m = outputQueue.poll(); dcpOutputBuffer.addAll(dcpMessageFactory.convertOutputMsg(m, getHost())); } } } catch (Exception e) { Logging.info(this, "interrupted " + getHostAndPort() + ": " + e.getLocalizedMessage()); break; } } try { dcpSocket.close(); heosSocket.close(); } catch (IOException e) { // nothing to do } super.stop(); Logging.info(this, "stopped " + getHostAndPort() + ":" + this); inputQueue.add(new OperationCommandMsg(OperationCommandMsg.Command.DOWN)); } private void sendDcpFormIphoneApp(final String rawCmd) { final String shortCmd = rawCmd.replace(" ", "%20"); try { final String fullCmd = ISCPMessage.getDcpGoformUrl(getHost(), DCP_HTTP_PORT, shortCmd); Logging.info(this, "DCP formiPhoneApp request: " + fullCmd); Utils.getUrlData(new URL(fullCmd), false); } catch (Exception ex) { Logging.info(this, "DCP formiPhoneApp error: " + ex.getLocalizedMessage()); } } private void sendDcpAppCommand(String rawCmd) { try { final String json = "{\"body\": \"" + ISCPMessage.getDcpAppCommand(rawCmd) + "\"}"; final byte[] out = json.getBytes(Utils.UTF_8); final URL url = new URL(ISCPMessage.getDcpGoformUrl(getHost(), DCP_HTTP_PORT, "AppCommand.xml")); final URLConnection con = url.openConnection(); final HttpURLConnection http = (HttpURLConnection) con; http.setRequestMethod("POST"); http.setDoOutput(true); http.setFixedLengthStreamingMode(out.length); http.setRequestProperty("Content-Type", "text/xml; charset=UTF-8"); http.connect(); OutputStream os = http.getOutputStream(); os.write(out); os.flush(); Logging.info(this, "DCP AppCommand POST request: " + url + json); } catch (Exception ex) { Logging.info(this, "DCP AppCommand error: " + ex.getLocalizedMessage()); } } private void sendDcpHeosRequest(@NonNull String msg) { if (heosSocket.getSocket() == null) { return; } if (msg.contains(ISCPMessage.DCP_HEOS_PID)) { if (heosPid == null) { return; } msg = msg.replace(ISCPMessage.DCP_HEOS_PID, Integer.toString(heosPid)); } try { Logging.info(this, ">> DCP HEOS sending: " + msg + " to " + heosSocket.getHostAndPort()); byte[] msgBin = msg.getBytes(Utils.UTF_8); final byte[] bytes = new byte[msgBin.length + 2]; System.arraycopy(msgBin, 0, bytes, 0, msgBin.length); bytes[msgBin.length] = (byte) CR; bytes[msgBin.length + 1] = (byte) LF; heosSocket.getSocket().write(ByteBuffer.wrap(bytes)); } catch (Exception ex) { Logging.info(this, "DCP HEOS error: " + ex.getLocalizedMessage()); } } private void sendDcpRawMsg(String msg) { try { byte[] msgBin = msg.getBytes(Utils.UTF_8); final byte[] bytes = new byte[msgBin.length + 1]; System.arraycopy(msgBin, 0, bytes, 0, msgBin.length); bytes[msgBin.length] = (byte) CR; dcpSocket.getSocket().write(ByteBuffer.wrap(bytes)); } catch (Exception ex) { Logging.info(this, "DCP error: " + ex.getLocalizedMessage()); } } @Override public boolean connectToServer(@NonNull String host, int port) { // Optional connection to HEOS port if (heosSocket.open(host, DCP_HEOS_PORT, connectionState.getContext(), false)) { sendDcpHeosRequest("heos://player/get_players"); } // Mandatory connection to AVR port return dcpSocket.open(host, port, connectionState.getContext(), true); } private void processInputData(ByteBuffer buffer, @NonNull final OnpcSocket socket) { byte[] bytes = socket.joinBuffer(buffer); int remaining = bytes.length; while (remaining > 0) { remaining = processDcpData(bytes, socket); if (remaining < 0) { // An error, nothing to process return; } if (remaining > 0) { bytes = Utils.catBuffer(bytes, bytes.length - remaining, remaining); } } } private int processDcpData(byte[] bytes, @NonNull final OnpcSocket onpcSocket) { int expectedSize = -1; for (int i = 0; i < bytes.length; i++) { if (bytes[i] == CR) { expectedSize = i; break; } } if (expectedSize <= 0) { final String logMsg = new String(bytes, Utils.UTF_8); if (logMsg.startsWith(DcpReceiverInformationMsg.DCP_COMMAND_PRESET)) { // A corner case: OPTPN has some time no end of message symbol Logging.info(this, "<< DCP warning: end of message not found: " + logMsg); expectedSize = logMsg.length(); } else { onpcSocket.setBuffer(bytes); return -1; } } if (expectedSize + 1 < bytes.length && bytes[expectedSize] == CR && bytes[expectedSize + 1] == LF) { // Consider possible LF after CR expectedSize++; } final byte[] stringBytes = expectedSize + 1 == bytes.length ? bytes : Utils.catBuffer(bytes, 0, expectedSize); final String dcpMsg = new String(stringBytes, Utils.UTF_8).trim(); final int remaining = Math.max(0, bytes.length - expectedSize - 1); boolean processed = false; if (dcpMsg.startsWith(DCP_HEOS_RESPONSE)) { processed = processHeosMsg(dcpMsg); } final ArrayList<ISCPMessage> messages = dcpMessageFactory.convertInputMsg(dcpMsg, heosPid); final boolean logIgnored = messages.size() == 1 && messages.get(0) instanceof TimeInfoMsg; if (!logIgnored) { final String resStr = processed ? " -> Processed" : (messages.isEmpty() ? " -> Ignored" : (messages.size() == 1 ? " -> " + messages.get(0) : " -> " + messages.size() + "msg")); Logging.info(this, "<< new DCP message " + dcpMsg + " from " + onpcSocket.getHostAndPort() + ", size=" + dcpMsg.length() + "B, remaining=" + remaining + "B" + resStr); } for (ISCPMessage m : messages) { m.setHostAndPort(this); inputQueue.add(m); } return remaining; } private boolean processHeosMsg(String heosMsg) { try { final String cmd = JsonPath.read(heosMsg, "$.heos.command"); // Device PID if (heosPid == null) { if ("player/get_players".equals(cmd)) { heosPid = JsonPath.read(heosMsg, "$.payload[0].pid"); Logging.info(this, "DCP HEOS PID received: " + heosPid); return true; } } // Events if (heosPid != null && "event/player_now_playing_changed".equals(cmd)) { final Map<String, String> tokens = ISCPMessage.parseHeosMessage(JsonPath.read(heosMsg, "$.heos.message")); final String pidStr = tokens.get("pid"); if (pidStr != null && heosPid.equals(Integer.valueOf(pidStr))) { sendDcpHeosRequest("heos://player/get_now_playing_media?pid=" + heosPid); return true; } } } catch (Exception ex) { Logging.info(this, "DCP HEOS error: " + ex.getLocalizedMessage()); } return false; } @Override public void sendMessage(EISCPMessage eiscpMessage) { outputQueue.add(eiscpMessage); } }
15,309
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
ConnectionIf.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/ConnectionIf.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp; import androidx.annotation.NonNull; public interface ConnectionIf { int ISCP_PORT = 60128; // Onkyo main and UDP port int DCP_PORT = 23; // Denon main port int DCP_UDP_PORT = 1900; // HEOS UDP port int DCP_HEOS_PORT = 1255; // HEOS main port int DCP_HTTP_PORT = 8080; // Denon-HTTP port (receiver info and command API) enum ProtoType { ISCP, // Integra Serial Communication Protocol (TCP:60128) DCP // Denon Control Protocol (TCP:23) } String EMPTY_HOST = ""; int EMPTY_PORT = -1; @NonNull String getHost(); int getPort(); @NonNull @SuppressWarnings("unused") String getHostAndPort(); }
1,380
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
DeviceList.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/DeviceList.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.RadioGroup; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.messages.BroadcastResponseMsg; import com.mkulesh.onpc.utils.AppTask; import com.mkulesh.onpc.utils.Logging; import com.mkulesh.onpc.utils.Utils; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.view.ContextThemeWrapper; import androidx.appcompat.widget.AppCompatRadioButton; public class DeviceList extends AppTask implements BroadcastSearch.EventListener { private final static int RESPONSE_NUMBER = 5; // Common properties private final Context context; private final ConnectionState connectionState; private BroadcastSearch searchEngine = null; // Devices properties public static class DeviceInfo { public final BroadcastResponseMsg message; private final boolean isFavorite; final int responses; boolean selected; DeviceInfo(@NonNull final BroadcastResponseMsg msg, final boolean isFavorite, int responses) { this.message = msg; this.isFavorite = isFavorite; this.responses = responses; this.selected = false; } } private final Map<String, DeviceInfo> devices = new TreeMap<>(); // Dialog properties private boolean dialogMode = false; private AlertDialog dialog = null; private RadioGroup dialogList = null; // Callbacks for dialogs public interface DialogEventListener { void onDeviceFound(BroadcastResponseMsg response); void noDevice(ConnectionState.FailureReason reason); } private DialogEventListener dialogEventListener = null; // Callback for background search public interface BackgroundEventListener { void onDeviceFound(DeviceInfo device); } private final BackgroundEventListener backgroundEventListener; private final List<BroadcastResponseMsg> favorites; public DeviceList(final Context context, final ConnectionState connectionState, final BackgroundEventListener backgroundEventListener, final List<BroadcastResponseMsg> favorites) { super(false); this.context = context; this.connectionState = connectionState; this.backgroundEventListener = backgroundEventListener; this.favorites = favorites; } public int getDevicesNumber() { synchronized (devices) { return devices.size(); } } public List<BroadcastResponseMsg> getDevices() { List<BroadcastResponseMsg> retValue = new ArrayList<>(); synchronized (devices) { for (DeviceInfo di : devices.values()) { retValue.add(new BroadcastResponseMsg(di.message)); } } return retValue; } public void start() { synchronized (devices) { devices.clear(); } updateFavorites(false); if (connectionState.isWifi()) { super.start(); Logging.info(this, "started"); searchEngine = new BroadcastSearch(connectionState, this); searchEngine.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null); } else { Logging.info(this, "device search skipped: no WiFi"); } } public void stop() { super.stop(); Logging.info(this, "stopped"); if (searchEngine != null) { searchEngine.stop(); } searchEngine = null; if (dialogMode) { dialogMode = false; if (dialog != null) { dialog.dismiss(); } dialog = null; dialogList = null; if (dialogEventListener != null) { BroadcastResponseMsg found = null; synchronized (devices) { for (DeviceInfo deviceInfo : devices.values()) { if (deviceInfo.selected) { found = new BroadcastResponseMsg(deviceInfo.message); break; } } } if (found != null) { dialogEventListener.onDeviceFound(found); } } dialogEventListener = null; } } public void updateFavorites(boolean callHandler) { synchronized (devices) { final List<String> toBeDeleted = new ArrayList<>(); for (Map.Entry<String, DeviceInfo> d : devices.entrySet()) { if (d.getValue().isFavorite) { toBeDeleted.add(d.getKey()); } } for (String key : toBeDeleted) { devices.remove(key); } for (BroadcastResponseMsg msg : favorites) { Logging.info(this, "Added favorite connection " + msg + ", handle=" + callHandler); final DeviceInfo newInfo = new DeviceInfo(msg, true, 0); devices.put(msg.getHostAndPort(), newInfo); if (callHandler && backgroundEventListener != null) { backgroundEventListener.onDeviceFound(newInfo); } } } } @Override public void onDeviceFound(BroadcastResponseMsg msg) { if (!msg.isValidConnection()) { Logging.info(this, " invalid response " + msg + ", ignored"); return; } Logging.info(this, " new response " + msg); synchronized (devices) { final String d = msg.getHostAndPort(); final DeviceInfo oldInfo = devices.get(d); DeviceInfo newInfo; if (oldInfo == null) { newInfo = new DeviceInfo(msg, false, 1); devices.put(d, newInfo); } else { final BroadcastResponseMsg newMsg = oldInfo.isFavorite ? oldInfo.message : msg; newInfo = new DeviceInfo(newMsg, oldInfo.isFavorite, oldInfo.responses + 1); devices.put(d, newInfo); } if (dialogMode) { updateRadioGroup(devices); } if (backgroundEventListener != null) { backgroundEventListener.onDeviceFound(newInfo); } if (!dialogMode) { int okDevice = 0; for (DeviceInfo di : devices.values()) { if ((di.isFavorite && di.responses == 0) || di.responses >= RESPONSE_NUMBER) { okDevice++; } } if (okDevice < devices.size()) { return; } Logging.info(this, " -> no more devices"); stop(); } } } @Override public void noDevice(ConnectionState.FailureReason reason) { if (dialogEventListener != null) { dialogEventListener.noDevice(reason); } stop(); } public void startSearchDialog(DialogEventListener listener) { if (!connectionState.isWifi()) { if (listener != null) { listener.noDevice(ConnectionState.FailureReason.NO_WIFI); } return; } dialogMode = true; dialogEventListener = listener; final FrameLayout frameView = new FrameLayout(context); final Drawable icon = Utils.getDrawable(context, R.drawable.media_item_search); Utils.setDrawableColorAttr(context, icon, android.R.attr.textColorSecondary); dialog = new AlertDialog.Builder(context) .setTitle(R.string.drawer_device_search) .setIcon(icon) .setCancelable(false) .setView(frameView) .setNegativeButton(context.getResources().getString(R.string.action_cancel), (d, which) -> stop()) .create(); dialog.getLayoutInflater().inflate(R.layout.dialog_broadcast_layout, frameView); dialogList = frameView.findViewById(R.id.broadcast_radio_group); synchronized (devices) { updateRadioGroup(devices); } if (!isActive()) { start(); } dialog.show(); Utils.fixDialogLayout(dialog, android.R.attr.textColorSecondary); } private void updateRadioGroup(final Map<String, DeviceInfo> devices) { if (dialogList != null) { dialogList.removeAllViews(); for (DeviceInfo deviceInfo : devices.values()) { deviceInfo.selected = false; if (deviceInfo.responses > 0) { final ContextThemeWrapper wrappedContext = new ContextThemeWrapper(context, R.style.RadioButtonStyle); final AppCompatRadioButton b = new AppCompatRadioButton(wrappedContext, null, 0); final LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); b.setLayoutParams(lp); b.setText(deviceInfo.message.getDescription()); b.setTextColor(Utils.getThemeColorAttr(context, android.R.attr.textColor)); b.setOnClickListener(v -> { deviceInfo.selected = true; stop(); }); dialogList.addView(b); } } dialogList.invalidate(); } } }
11,153
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
BroadcastSearch.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/BroadcastSearch.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp; import android.os.AsyncTask; import android.os.StrictMode; import com.mkulesh.onpc.iscp.messages.BroadcastResponseMsg; import com.mkulesh.onpc.utils.Logging; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.Arrays; import java.util.Calendar; import java.util.concurrent.atomic.AtomicBoolean; public class BroadcastSearch extends AsyncTask<Void, BroadcastResponseMsg, Void> { private final static int TIMEOUT = 3000; // Connection state private final ConnectionState connectionState; // Callbacks public interface EventListener { void onDeviceFound(BroadcastResponseMsg response); void noDevice(ConnectionState.FailureReason reason); } private EventListener eventListener; // Common properties private final AtomicBoolean active = new AtomicBoolean(); private ConnectionState.FailureReason failureReason = null; BroadcastSearch(final ConnectionState connectionState, final EventListener eventListener) { this.connectionState = connectionState; this.eventListener = eventListener; active.set(false); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } @Override protected void onPreExecute() { super.onPreExecute(); active.set(true); } public void stop() { synchronized (active) { active.set(false); eventListener = null; } } private boolean isStopped() { if (!connectionState.isNetwork()) { failureReason = ConnectionState.FailureReason.NO_NETWORK; return true; } if (!connectionState.isWifi()) { failureReason = ConnectionState.FailureReason.NO_WIFI; return true; } // no reason for events below if (isCancelled() || !connectionState.isActive()) { return true; } synchronized (active) { return !active.get(); } } @Override protected Void doInBackground(Void... params) { Logging.info(this, "started, network=" + connectionState.isNetwork() + ", wifi=" + connectionState.isWifi()); final Character[] models = new Character[]{ 'x', 'p' }; try { final DatagramSocket iscpSocket = prepareSocket(ConnectionIf.ISCP_PORT); final DatagramSocket dcpSocket = prepareSocket(ConnectionIf.DCP_UDP_PORT); final byte[] response = new byte[1024]; while (!isStopped()) { requestIscp(iscpSocket, models[0]); requestIscp(iscpSocket, models[1]); requestDcp(dcpSocket); final long startTime = Calendar.getInstance().getTimeInMillis(); while (Calendar.getInstance().getTimeInMillis() < startTime + TIMEOUT) { if (isStopped()) { break; } getIscpResponce(iscpSocket, response); getDcpResponce(dcpSocket, response); } } iscpSocket.close(); dcpSocket.close(); } catch (Exception e) { Logging.info(this, "Can not open socket: " + e); } Logging.info(this, "stopped"); return null; } private DatagramSocket prepareSocket(int port) throws Exception { final DatagramSocket s = new DatagramSocket(null); s.setReuseAddress(true); s.setBroadcast(true); s.setSoTimeout(500); s.bind(new InetSocketAddress(port)); return s; } private EISCPMessage convertResponse(byte[] response) { try { final int startIndex = EISCPMessage.getMsgStartIndex(response); if (startIndex != 0) { Logging.info(this, " -> unexpected position of start index: " + startIndex); return null; } final int hSize = EISCPMessage.getHeaderSize(response, startIndex); final int dSize = EISCPMessage.getDataSize(response, startIndex); return new EISCPMessage(0, response, startIndex, hSize, dSize); } catch (Exception e) { return null; } } private void requestIscp(DatagramSocket socket, final Character modelCategoryId) { final EISCPMessage m = new EISCPMessage(modelCategoryId, "ECN", "QSTN"); final byte[] bytes = m.getBytes(); try { final InetAddress target = InetAddress.getByName("255.255.255.255"); final DatagramPacket p = new DatagramPacket(bytes, bytes.length, target, ConnectionIf.ISCP_PORT); socket.send(p); Logging.info(this, "message " + m + " for category '" + modelCategoryId + "' send to " + target + ", wait response for " + TIMEOUT + "ms"); } catch (Exception e) { Logging.info(BroadcastSearch.this, " -> can not send request: " + e); } } private void getIscpResponce(final DatagramSocket socket, final byte[] response) { try { Arrays.fill(response, (byte) 0); final DatagramPacket p2 = new DatagramPacket(response, response.length); socket.receive(p2); if (p2.getAddress() == null) { return; } final EISCPMessage msg = convertResponse(response); if (msg == null || msg.getParameters() == null) { return; } if (msg.getParameters().equals("QSTN")) { return; } final BroadcastResponseMsg responseMessage = new BroadcastResponseMsg(p2.getAddress(), msg); if (responseMessage.isValidConnection()) { publishProgress(responseMessage); } } catch (Exception e) { // nothing to do } } private void requestDcp(DatagramSocket socket) { final String host = "239.255.255.250"; final String schema = "schemas-denon-com:device"; final String request = "M-SEARCH * HTTP/1.1\r\n" + "HOST: " + host + ":" + ConnectionIf.DCP_UDP_PORT + "\r\n" + "MAN: \"ssdp:discover\"\r\n" + "MX: 10\r\n" + "ST: urn:" + schema + ":ACT-Denon:1\r\n\r\n"; final byte[] bytes = request.getBytes(); try { final InetAddress target = InetAddress.getByName(host); final DatagramPacket p = new DatagramPacket(bytes, bytes.length, target, ConnectionIf.DCP_UDP_PORT); socket.send(p); Logging.info(this, "message M-SEARCH for category send to " + target + ", wait response for " + TIMEOUT + "ms"); } catch (Exception e) { Logging.info(BroadcastSearch.this, " -> can not send request: " + e); } } private void getDcpResponce(DatagramSocket socket, final byte[] response) { final String schema = "schemas-denon-com:device"; try { Arrays.fill(response, (byte) 0); final DatagramPacket p2 = new DatagramPacket(response, response.length); socket.receive(p2); if (p2.getAddress() == null || p2.getAddress().getHostAddress() == null) { return; } final String responseStr = new String(response); if (responseStr.contains(schema)) { final BroadcastResponseMsg responseMessage = new BroadcastResponseMsg(p2.getAddress().getHostAddress(), 23, "Denon-Heos AVR"); if (responseMessage.isValidConnection()) { publishProgress(responseMessage); } } } catch (Exception e) { // nothing to do } } @Override protected void onProgressUpdate(BroadcastResponseMsg... result) { if (result == null || result.length == 0) { return; } final BroadcastResponseMsg msg = result[0]; if (eventListener != null) { eventListener.onDeviceFound(msg); } } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); if (failureReason != null) { Logging.info(this, "Device not found: " + failureReason); if (eventListener != null) { eventListener.noDevice(failureReason); } } } }
9,766
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
StateManager.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/StateManager.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp; import android.content.Context; import android.os.AsyncTask; import android.os.StrictMode; import com.mkulesh.onpc.config.CfgFavoriteShortcuts; import com.mkulesh.onpc.iscp.messages.AlbumNameMsg; import com.mkulesh.onpc.iscp.messages.AmpOperationCommandMsg; import com.mkulesh.onpc.iscp.messages.ArtistNameMsg; import com.mkulesh.onpc.iscp.messages.AudioInformationMsg; import com.mkulesh.onpc.iscp.messages.AudioMutingMsg; import com.mkulesh.onpc.iscp.messages.AutoPowerMsg; import com.mkulesh.onpc.iscp.messages.BroadcastResponseMsg; import com.mkulesh.onpc.iscp.messages.CenterLevelCommandMsg; import com.mkulesh.onpc.iscp.messages.DcpAudioRestorerMsg; import com.mkulesh.onpc.iscp.messages.DcpEcoModeMsg; import com.mkulesh.onpc.iscp.messages.DcpMediaContainerMsg; import com.mkulesh.onpc.iscp.messages.DcpMediaEventMsg; import com.mkulesh.onpc.iscp.messages.DcpMediaItemMsg; import com.mkulesh.onpc.iscp.messages.DcpReceiverInformationMsg; import com.mkulesh.onpc.iscp.messages.DcpSearchCriteriaMsg; import com.mkulesh.onpc.iscp.messages.DcpTunerModeMsg; import com.mkulesh.onpc.iscp.messages.DigitalFilterMsg; import com.mkulesh.onpc.iscp.messages.DimmerLevelMsg; import com.mkulesh.onpc.iscp.messages.DirectCommandMsg; import com.mkulesh.onpc.iscp.messages.DisplayModeMsg; import com.mkulesh.onpc.iscp.messages.FileFormatMsg; import com.mkulesh.onpc.iscp.messages.FirmwareUpdateMsg; import com.mkulesh.onpc.iscp.messages.FriendlyNameMsg; import com.mkulesh.onpc.iscp.messages.GoogleCastAnalyticsMsg; import com.mkulesh.onpc.iscp.messages.GoogleCastVersionMsg; import com.mkulesh.onpc.iscp.messages.HdmiCecMsg; import com.mkulesh.onpc.iscp.messages.InputSelectorMsg; import com.mkulesh.onpc.iscp.messages.JacketArtMsg; import com.mkulesh.onpc.iscp.messages.LateNightCommandMsg; import com.mkulesh.onpc.iscp.messages.ListInfoMsg; import com.mkulesh.onpc.iscp.messages.ListTitleInfoMsg; import com.mkulesh.onpc.iscp.messages.ListeningModeMsg; import com.mkulesh.onpc.iscp.messages.MasterVolumeMsg; import com.mkulesh.onpc.iscp.messages.MenuStatusMsg; import com.mkulesh.onpc.iscp.messages.MultiroomDeviceInformationMsg; import com.mkulesh.onpc.iscp.messages.MusicOptimizerMsg; import com.mkulesh.onpc.iscp.messages.NetworkServiceMsg; import com.mkulesh.onpc.iscp.messages.NetworkStandByMsg; import com.mkulesh.onpc.iscp.messages.OperationCommandMsg; import com.mkulesh.onpc.iscp.messages.PhaseMatchingBassMsg; import com.mkulesh.onpc.iscp.messages.PlayStatusMsg; import com.mkulesh.onpc.iscp.messages.PowerStatusMsg; import com.mkulesh.onpc.iscp.messages.PresetCommandMsg; import com.mkulesh.onpc.iscp.messages.PresetMemoryMsg; import com.mkulesh.onpc.iscp.messages.PrivacyPolicyStatusMsg; import com.mkulesh.onpc.iscp.messages.RadioStationNameMsg; import com.mkulesh.onpc.iscp.messages.ReceiverInformationMsg; import com.mkulesh.onpc.iscp.messages.ServiceType; import com.mkulesh.onpc.iscp.messages.SleepSetCommandMsg; import com.mkulesh.onpc.iscp.messages.SpeakerACommandMsg; import com.mkulesh.onpc.iscp.messages.SpeakerBCommandMsg; import com.mkulesh.onpc.iscp.messages.SubwooferLevelCommandMsg; import com.mkulesh.onpc.iscp.messages.TimeInfoMsg; import com.mkulesh.onpc.iscp.messages.TitleNameMsg; import com.mkulesh.onpc.iscp.messages.ToneCommandMsg; import com.mkulesh.onpc.iscp.messages.TrackInfoMsg; import com.mkulesh.onpc.iscp.messages.TuningCommandMsg; import com.mkulesh.onpc.iscp.messages.VideoInformationMsg; import com.mkulesh.onpc.iscp.messages.XmlListInfoMsg; import com.mkulesh.onpc.iscp.scripts.MessageScript; import com.mkulesh.onpc.iscp.scripts.MessageScriptIf; import com.mkulesh.onpc.utils.Logging; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Timer; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import androidx.annotation.NonNull; import androidx.annotation.Nullable; public class StateManager extends AsyncTask<Void, Void, Void> { private static final long GUI_UPDATE_DELAY = 500; public interface StateListener { void onStateChanged(State state, @Nullable final HashSet<State.ChangeType> eventChanges); void onManagerStopped(); void onDeviceDisconnected(); } private final DeviceList deviceList; private final ConnectionState connectionState; private final Map<String, MessageChannel> multiroomChannels = new HashMap<>(); private final StateListener stateListener; private final MessageChannel messageChannel; private final State state; private final AtomicBoolean requestXmlList = new AtomicBoolean(); private final AtomicBoolean playbackMode = new AtomicBoolean(); private final AtomicInteger skipNextTimeMsg = new AtomicInteger(); private final AtomicBoolean requestRIonPreset = new AtomicBoolean(); private final HashSet<State.ChangeType> eventChanges = new HashSet<>(); private int xmlReqId = 0; private ISCPMessage circlePlayQueueMsg = null; private final static String[] trackStateQueries = new String[]{ ArtistNameMsg.CODE, AlbumNameMsg.CODE, TitleNameMsg.CODE, FileFormatMsg.CODE, TrackInfoMsg.CODE, TimeInfoMsg.CODE, MenuStatusMsg.CODE }; private final static String[] avInfoQueries = new String[]{ AudioInformationMsg.CODE, VideoInformationMsg.CODE }; private final static String[] multiroomQueries = new String[]{ MultiroomDeviceInformationMsg.CODE, FriendlyNameMsg.CODE }; private final AtomicBoolean keepPlaybackMode = new AtomicBoolean(); private final boolean useBmpImages; private final BlockingQueue<ISCPMessage> inputQueue = new ArrayBlockingQueue<>(MessageChannel.QUEUE_SIZE, true); public final static OperationCommandMsg LIST_MSG = new OperationCommandMsg(OperationCommandMsg.Command.LIST); // MessageScript processor private final ArrayList<MessageScriptIf> messageScripts; public StateManager(final DeviceList deviceList, final ConnectionState connectionState, final StateListener stateListener, final String host, final int port, final int zone, final boolean keepPlaybackMode, final String savedReceiverInformation, final @NonNull ArrayList<MessageScriptIf> messageScripts) throws Exception { this.deviceList = deviceList; this.connectionState = connectionState; this.stateListener = stateListener; messageChannel = port == ConnectionIf.DCP_PORT ? new MessageChannelDcp(zone, connectionState, inputQueue) : new MessageChannelIscp(connectionState, inputQueue); if (!messageChannel.connectToServer(host, port)) { throw new Exception("Cannot connect to server"); } state = new State(messageChannel.getProtoType(), messageChannel.getHost(), messageChannel.getPort(), zone); // In LTE mode, always use BMP images instead of links since direct links // can be not available useBmpImages = !connectionState.isWifi(); setPlaybackMode(keepPlaybackMode); if (savedReceiverInformation != null) { try { state.process(new ReceiverInformationMsg( new EISCPMessage(ReceiverInformationMsg.CODE, savedReceiverInformation)), /*showInfo=*/ false); } catch (Exception ex) { // nothing to do } } this.messageScripts = messageScripts; messageChannel.start(); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null); // initial call os the message scripts for (MessageScriptIf script : messageScripts) { if (script.isValid()) { script.start(state, messageChannel); } } } private void activateScript(final MessageScript messageScript) { for (MessageScriptIf script : messageScripts) { if (script instanceof MessageScript) { messageScripts.remove(script); } } if (messageScript.isValid()) { messageScripts.add(messageScript); messageScript.start(state, messageChannel); } } public StateManager(final ConnectionState connectionState, final StateListener stateListener, final int zone) { this.deviceList = null; this.connectionState = connectionState; this.stateListener = stateListener; messageChannel = new MessageChannelIscp(connectionState, inputQueue); state = new MockupState(zone); useBmpImages = false; setPlaybackMode(false); messageScripts = new ArrayList<>(); messageChannel.start(); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null); } public void setPlaybackMode(boolean flag) { keepPlaybackMode.set(flag); } public void stop() { messageChannel.stop(); for (MessageChannel m : multiroomChannels.values()) { m.stop(); } } @NonNull public final State getState() { return state; } @Override protected Void doInBackground(Void... params) { Logging.info(this, "started: " + this); if (state.protoType == ConnectionIf.ProtoType.ISCP) { requestInitialIscpState(); } else { requestInitialDcpState(); } final BlockingQueue<Timer> timerQueue = new ArrayBlockingQueue<>(1, true); skipNextTimeMsg.set(0); requestXmlList.set(false); playbackMode.set(false); requestRIonPreset.set(false); while (true) { try { if (!messageChannel.isActive()) { Logging.info(this, "message channel stopped"); break; } final ISCPMessage msg = inputQueue.take(); if (msg instanceof ZonedMessage) { final ZonedMessage zMsg = (ZonedMessage) msg; if (zMsg.zoneIndex != state.getActiveZone()) { Logging.info(this, "message ignored: non active zone " + zMsg.zoneIndex); continue; } } boolean changed = false; try { changed = messageChannel.getProtoType() == ConnectionIf.ProtoType.ISCP ? processIscpMessage(msg) : processDcpMessage(msg); for (MessageScriptIf script : messageScripts) { if (script.isValid()) { script.processMessage(msg, state, messageChannel); } } } catch (Exception e) { Logging.info(this, "cannot process message: " + e.getLocalizedMessage()); for (StackTraceElement el : e.getStackTrace()) { Logging.info(this, el.toString()); } } if (msg instanceof BroadcastResponseMsg && deviceList != null) { handleMultiroom(); } if (changed && timerQueue.isEmpty()) { final Timer t = new Timer(); timerQueue.add(t); t.schedule(new java.util.TimerTask() { @Override public void run() { timerQueue.poll(); publishProgress(); } }, GUI_UPDATE_DELAY); } } catch (Exception e) { Logging.info(this, "interrupted: " + e.getLocalizedMessage()); break; } } while (true) { int activeCount = 0; for (MessageChannel m : multiroomChannels.values()) { if (m.isActive()) { activeCount++; } } if (activeCount == 0) { break; } } Logging.info(this, "stopped: " + this); stateListener.onManagerStopped(); return null; } private void requestInitialIscpState() { messageChannel.sendMessage( new EISCPMessage(JacketArtMsg.CODE, useBmpImages ? JacketArtMsg.TYPE_BMP : JacketArtMsg.TYPE_LINK)); final String[] powerStateQueries = new String[]{ ReceiverInformationMsg.CODE, MultiroomDeviceInformationMsg.CODE, PowerStatusMsg.ZONE_COMMANDS[state.getActiveZone()], FriendlyNameMsg.CODE, FirmwareUpdateMsg.CODE, GoogleCastVersionMsg.CODE, PrivacyPolicyStatusMsg.CODE, ListeningModeMsg.CODE }; sendQueries(powerStateQueries, "requesting power state..."); } private void requestInitialDcpState() { if (requestDcpReceiverInfo(ConnectionIf.DCP_HTTP_PORT)) { return; } // Fallback to the port 80 for older models if (!requestDcpReceiverInfo(80)) { // request DcpReceiverInformationMsg here since no ReceiverInformation exists // otherwise it will be requested when ReceiverInformation is processed sendMessage(new DcpReceiverInformationMsg(DcpReceiverInformationMsg.QueryType.FULL)); final String[] powerStateQueries = new String[]{ PowerStatusMsg.ZONE_COMMANDS[state.getActiveZone()], }; sendQueries(powerStateQueries, "requesting DCP default state..."); } } private boolean requestDcpReceiverInfo(final int port) { try { inputQueue.add(new ReceiverInformationMsg(messageChannel.getHost(), port)); return true; } catch (Exception ex) { Logging.info(this, "Cannot load DCP receiver information: " + ex.getLocalizedMessage()); } return false; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); stateListener.onDeviceDisconnected(); } private boolean processIscpMessage(@NonNull ISCPMessage msg) { // skip time message, is necessary if (msg instanceof TimeInfoMsg && skipNextTimeMsg.get() > 0) { skipNextTimeMsg.set(Math.max(0, skipNextTimeMsg.get() - 1)); return false; } final PlayStatusMsg.PlayStatus playStatus = state.playStatus; final State.ChangeType changed = state.update(msg); if (changed != State.ChangeType.NONE) { eventChanges.add(changed); } // no further message handling, if power off if (!state.isOn()) { return changed != State.ChangeType.NONE; } // on TrackInfoMsg, always do XML state request upon the next ListTitleInfoMsg if (msg instanceof TrackInfoMsg) { requestXmlList.set(true); return true; } // corner case: delayed USB initialization at power on if (msg instanceof ListInfoMsg) { if (state.isUsb() && state.isTopLayer() && !state.listInfoConsistent()) { Logging.info(this, "requesting XML list state for USB..."); messageChannel.sendMessage( new EISCPMessage(XmlListInfoMsg.CODE, XmlListInfoMsg.getListedData( xmlReqId++, state.numberOfLayers, 0, state.numberOfItems))); } } // Issue LIST command upon PlayStatusMsg if PlaybackMode is active if (msg instanceof ListTitleInfoMsg) { playbackMode.set(state.isPlaybackMode()); } if (!keepPlaybackMode.get() && msg instanceof PlayStatusMsg && playbackMode.get() && state.isPlaying() && state.serviceType != ServiceType.TUNEIN_RADIO) { // Notes for not requesting list mode for some service Types: // #51: List mode stops playing TUNEIN_RADIO for some models Logging.info(this, "requesting list mode..."); messageChannel.sendMessage(LIST_MSG.getCmdMsg()); playbackMode.set(false); } // request receiver information after radio preset is memorized if ((msg instanceof PresetCommandMsg || msg instanceof PresetMemoryMsg) && requestRIonPreset.get()) { requestRIonPreset.set(false); final String[] queries = new String[]{ ReceiverInformationMsg.CODE }; sendQueries(queries, "requesting receiver information..."); } // no further message handling, if no changes are detected if (changed == State.ChangeType.NONE) { if (msg instanceof ListTitleInfoMsg && requestXmlList.get()) { requestXmlListState((ListTitleInfoMsg) msg); } return false; } if (msg instanceof PowerStatusMsg) { // #58: delayed response for InputSelectorMsg was observed: // Send this request first final String toneCommand = state.getActiveZone() < ToneCommandMsg.ZONE_COMMANDS.length ? ToneCommandMsg.ZONE_COMMANDS[state.getActiveZone()] : null; final String[] playStateQueries = new String[]{ // PlaybackState InputSelectorMsg.ZONE_COMMANDS[state.getActiveZone()], PlayStatusMsg.CODE, // DeviceSettingsState DimmerLevelMsg.CODE, DigitalFilterMsg.CODE, MusicOptimizerMsg.CODE, AutoPowerMsg.CODE, HdmiCecMsg.CODE, PhaseMatchingBassMsg.CODE, SleepSetCommandMsg.CODE, GoogleCastAnalyticsMsg.CODE, SpeakerACommandMsg.ZONE_COMMANDS[state.getActiveZone()], SpeakerBCommandMsg.ZONE_COMMANDS[state.getActiveZone()], LateNightCommandMsg.CODE, NetworkStandByMsg.CODE, // SoundControlState AudioMutingMsg.ZONE_COMMANDS[state.getActiveZone()], MasterVolumeMsg.ZONE_COMMANDS[state.getActiveZone()], toneCommand, SubwooferLevelCommandMsg.CODE, CenterLevelCommandMsg.CODE, ListeningModeMsg.CODE, DirectCommandMsg.CODE, // RadioState PresetCommandMsg.ZONE_COMMANDS[state.getActiveZone()], TuningCommandMsg.ZONE_COMMANDS[state.getActiveZone()], RadioStationNameMsg.CODE }; sendQueries(playStateQueries, "requesting play state..."); sendQueries(avInfoQueries, "requesting audio/video info..."); requestListState(); } if (msg instanceof InputSelectorMsg) { if (state.isCdInput()) { final String[] cdStateQueries = new String[]{ PlayStatusMsg.CD_CODE }; sendQueries(cdStateQueries, "requesting CD state..."); } sendQueries(avInfoQueries, "requesting audio/video info..."); } if (msg instanceof PlayStatusMsg && playStatus != state.playStatus) { if (state.isPlaying()) { sendQueries(trackStateQueries, "requesting track state..."); sendQueries(avInfoQueries, "requesting audio/video info..."); // Some devices (like TX-8150) does not proved cover image; // we shall specially request it: if (state.getModel().equals("TX-8150") || state.serviceType == ServiceType.SPOTIFY) { messageChannel.sendMessage( new EISCPMessage(JacketArtMsg.CODE, JacketArtMsg.REQUEST)); } if (state.isMediaEmpty()) { requestListState(); } } else if (!state.isPopupMode()) { requestListState(); } } if (msg instanceof ListTitleInfoMsg) { final ListTitleInfoMsg liMsg = (ListTitleInfoMsg) msg; if (circlePlayQueueMsg != null && liMsg.getNumberOfItems() > 0) { sendPlayQueueMsg(circlePlayQueueMsg, true); } else { circlePlayQueueMsg = null; requestXmlListState(liMsg); } } // #276 DAB channel frequency is some time invalid: an additional request // is necessary for NS-6170 in order to receive DAB frequency. if (msg instanceof RadioStationNameMsg) { final String[] tunerStatusQueries = new String[]{ TuningCommandMsg.ZONE_COMMANDS[state.getActiveZone()] }; sendQueries(tunerStatusQueries, "requesting radio frequency..."); } // check privacy policy but do not accept it automatically if (msg instanceof PrivacyPolicyStatusMsg) { final PrivacyPolicyStatusMsg ppMsg = (PrivacyPolicyStatusMsg) msg; if (!ppMsg.isPolicySet(PrivacyPolicyStatusMsg.Status.ONKYO)) { Logging.info(this, "ONKYO policy is not accepted"); } if (!ppMsg.isPolicySet(PrivacyPolicyStatusMsg.Status.GOOGLE)) { Logging.info(this, "GOOGLE policy is not accepted"); } if (!ppMsg.isPolicySet(PrivacyPolicyStatusMsg.Status.SUE)) { Logging.info(this, "SUE policy is not accepted"); } } return true; } private boolean processDcpMessage(ISCPMessage msg) { final PlayStatusMsg.PlayStatus playStatus = state.playStatus; final State.ChangeType changed = state.update(msg); if (changed != State.ChangeType.NONE) { eventChanges.add(changed); } if (msg instanceof ReceiverInformationMsg) { final ReceiverInformationMsg ri = (ReceiverInformationMsg) msg; if (ri.getPresetList().isEmpty()) { sendMessage(new DcpReceiverInformationMsg(DcpReceiverInformationMsg.QueryType.FULL)); } else { sendMessage(new DcpReceiverInformationMsg(DcpReceiverInformationMsg.QueryType.SHORT)); } // In order to reduce waiting time for track info, request track information first final String[] powerStateQueries = new String[]{ DcpMediaItemMsg.CODE, FirmwareUpdateMsg.CODE, PowerStatusMsg.ZONE_COMMANDS[state.getActiveZone()], FriendlyNameMsg.CODE }; sendQueries(powerStateQueries, "requesting DCP power state..."); } if (msg instanceof DcpMediaEventMsg) { if (msg.getData().equals(DcpMediaEventMsg.HEOS_EVENT_QUEUE) && state.isOn() && state.serviceType == ServiceType.DCP_PLAYQUEUE) { Logging.info(this, "DCP: requesting queue state..."); sendMessage(new NetworkServiceMsg(state.serviceType)); } if (msg.getData().equals(DcpMediaEventMsg.HEOS_EVENT_SERVICEOPT) && state.isOn() && !state.dcpMediaPath.isEmpty()) { Logging.info(this, "DCP: requesting media list..."); sendMessage(state.dcpMediaPath.get(state.dcpMediaPath.size() - 1)); } } // no further message handling, if power off if (!state.isOn()) { state.inputType = InputSelectorMsg.InputType.NONE; return changed != State.ChangeType.NONE; } // no further message handling, if no changes are detected if (changed == State.ChangeType.NONE) { return false; } if (msg instanceof PowerStatusMsg) { final String toneCommand = state.getActiveZone() < ToneCommandMsg.ZONE_COMMANDS.length ? ToneCommandMsg.ZONE_COMMANDS[state.getActiveZone()] : null; final String[] playStateQueries = new String[]{ // PlaybackState PlayStatusMsg.CODE, InputSelectorMsg.ZONE_COMMANDS[state.getActiveZone()], // SoundControlState AudioMutingMsg.ZONE_COMMANDS[state.getActiveZone()], MasterVolumeMsg.ZONE_COMMANDS[state.getActiveZone()], toneCommand, ListeningModeMsg.CODE, // DeviceSettingsState DimmerLevelMsg.CODE, SleepSetCommandMsg.CODE, DcpEcoModeMsg.CODE, DcpAudioRestorerMsg.CODE, HdmiCecMsg.CODE, // repeat InputSelectorMsg since the first request is sometime ignored InputSelectorMsg.ZONE_COMMANDS[state.getActiveZone()], }; // After transmitting a power on COMMAND(PWON, the next COMMAND // shall be transmitted at least 1 second later final int REQUEST_DELAY = 1500; final Timer t = new Timer(); t.schedule(new java.util.TimerTask() { @Override public void run() { sendQueries(playStateQueries, "DCP: requesting play state with delay " + REQUEST_DELAY + "ms..."); } }, REQUEST_DELAY); } if (msg instanceof InputSelectorMsg) { if (((InputSelectorMsg) msg).getInputType() == InputSelectorMsg.InputType.DCP_TUNER) { final String[] tunerStatusQueries = new String[]{ DcpTunerModeMsg.CODE }; sendQueries(tunerStatusQueries, "DCP: requesting tuner state..."); } else if (((InputSelectorMsg) msg).getInputType() == InputSelectorMsg.InputType.DCP_NET) { state.setDcpNetTopLayer(); final String[] playStatusQueries = new String[]{ DcpMediaItemMsg.CODE, PlayStatusMsg.CODE }; sendQueries(playStatusQueries, "DCP: requesting play state..."); } } if (msg instanceof DcpMediaContainerMsg) { final DcpMediaContainerMsg mc = (DcpMediaContainerMsg) msg; final int currItems = mc.getStart() + mc.getItems().size(); if (currItems < mc.getCount() && mc.getCid().equals(state.mediaListCid)) { Logging.info(this, "Requesting DCP media list: currItems=" + currItems + ", count=" + mc.getCount()); final DcpMediaContainerMsg newMc = new DcpMediaContainerMsg(mc); newMc.setAid(""); newMc.setStart(currItems); sendMessage(newMc); } if (mc.getStart() == 0 && !state.mediaListSid.isEmpty() && state.mediaListSid.equals(mc.getSid())) { // #290: Additional DcpSearchCriteriaMsg shall be sent in order to request valid search criteria for the service sendMessage(new DcpSearchCriteriaMsg(mc.getSid())); } } if (msg instanceof DcpTunerModeMsg) { final String[] tunerStatusQueries = new String[]{ PresetCommandMsg.ZONE_COMMANDS[state.getActiveZone()], TuningCommandMsg.ZONE_COMMANDS[state.getActiveZone()], RadioStationNameMsg.CODE }; sendQueries(tunerStatusQueries, "DCP: requesting radio playback state..."); } if (msg instanceof PlayStatusMsg && playStatus != state.playStatus && state.isPlaying()) { final String[] trackStatusQueries = new String[]{ DcpMediaItemMsg.CODE }; sendQueries(trackStatusQueries, "DCP: requesting track state..."); } return true; } @Override protected void onProgressUpdate(Void... result) { stateListener.onStateChanged(state, eventChanges); eventChanges.clear(); } private void requestListState() { Logging.info(this, "requesting list state..."); requestXmlList.set(true); messageChannel.sendMessage( new EISCPMessage(ListTitleInfoMsg.CODE, EISCPMessage.QUERY)); } private void requestXmlListState(final ListTitleInfoMsg liMsg) { requestXmlList.set(false); if (liMsg.isNetTopService() || state.isRadioInput()) { Logging.info(this, "requesting XML list state skipped"); } else if (liMsg.getUiType() == ListTitleInfoMsg.UIType.PLAYBACK || liMsg.getUiType() == ListTitleInfoMsg.UIType.POPUP) { Logging.info(this, "requesting XML list state skipped"); } else if (liMsg.isXmlListTopService() || liMsg.getNumberOfLayers() > 0 || liMsg.getUiType() == ListTitleInfoMsg.UIType.MENU) { Logging.info(this, "requesting XML list state"); messageChannel.sendMessage( new EISCPMessage(XmlListInfoMsg.CODE, XmlListInfoMsg.getListedData( xmlReqId++, liMsg.getNumberOfLayers(), 0, liMsg.getNumberOfItems()))); } } public void sendMessage(final ISCPMessage msg) { Logging.info(this, "sending message: " + msg.toString()); if (msg.isMultiline()) { msg.logParameters(); } circlePlayQueueMsg = null; if (msg.hasImpactOnMediaList() || (msg instanceof DisplayModeMsg && !state.isPlaybackMode())) { requestXmlList.set(true); } final EISCPMessage cmdMsg = msg.getCmdMsg(); if (cmdMsg != null) { messageChannel.sendMessage(cmdMsg); } } public void sendMessageToGroup(final ISCPMessage msg) { Logging.info(this, "sending message to group: " + msg.toString()); for (MessageChannel m : multiroomChannels.values()) { m.sendMessage(msg.getCmdMsg()); } messageChannel.sendMessage(msg.getCmdMsg()); } public void sendPlayQueueMsg(ISCPMessage msg, boolean repeat) { if (msg == null) { return; } if (repeat) { Logging.info(this, "starting repeat mode: " + msg); circlePlayQueueMsg = msg; } requestXmlList.set(true); messageChannel.sendMessage(msg.getCmdMsg()); } public void requestSkipNextTimeMsg(final int number) { skipNextTimeMsg.set(number); } public void requestRIonPreset(final boolean flag) { requestRIonPreset.set(flag); } public void sendQueries(final String[] queries, final String purpose) { Logging.info(this, purpose); for (String code : queries) { if (code == null) { continue; } messageChannel.sendMessage( new EISCPMessage(code, EISCPMessage.QUERY)); } } public void sendTrackCmd(OperationCommandMsg.Command cmd, boolean doReturn) { final OperationCommandMsg msg = new OperationCommandMsg( ReceiverInformationMsg.DEFAULT_ACTIVE_ZONE, cmd.toString()); sendTrackMsg(msg, doReturn); } public void sendTrackMsg(final OperationCommandMsg msg, boolean doReturn) { Logging.info(this, "sending track cmd: " + msg.toString()); if (!state.isPlaybackMode()) { messageChannel.sendMessage(LIST_MSG.getCmdMsg()); } messageChannel.sendMessage(msg.getCmdMsg()); if (doReturn) { messageChannel.sendMessage(LIST_MSG.getCmdMsg()); } } public void sendDcpMediaCmd(DcpMediaContainerMsg mc, int aid) { final DcpMediaContainerMsg mc1 = new DcpMediaContainerMsg(mc); mc1.setAid(Integer.toString(aid)); messageChannel.sendMessage(mc1.getCmdMsg()); } public ISCPMessage getReturnMessage() { if (state.protoType == ConnectionIf.ProtoType.DCP && state.dcpMediaPath.size() > 1) { return state.dcpMediaPath.get(state.dcpMediaPath.size() - 2); } return new OperationCommandMsg(OperationCommandMsg.Command.RETURN); } public void inform(BroadcastResponseMsg message) { inputQueue.add(message); } private void handleMultiroom() { for (BroadcastResponseMsg msg : deviceList.getDevices()) { if (!msg.isValidConnection()) { continue; } if (msg.fromHost(messageChannel)) { continue; } if (multiroomChannels.containsKey(msg.getHostAndPort())) { continue; } Logging.info(this, "connecting to multiroom device: " + msg.getHostAndPort()); final MessageChannel m = msg.getPort() == ConnectionIf.DCP_PORT ? new MessageChannelDcp(ReceiverInformationMsg.DEFAULT_ACTIVE_ZONE, connectionState, inputQueue) : new MessageChannelIscp(connectionState, inputQueue); for (String code : multiroomQueries) { m.addAllowedMessage(code); m.sendMessage(new EISCPMessage(code, EISCPMessage.QUERY)); } if (m.connectToServer(msg.getHost(), msg.getPort())) { multiroomChannels.put(msg.getHostAndPort(), m); m.start(); } } } public void changeMasterVolume(@NonNull final String soundControlStr, boolean isUp) { final State.SoundControlType soundControl = state.soundControlType( soundControlStr, state.getActiveZoneInfo()); switch (soundControl) { case DEVICE_BUTTONS: case DEVICE_SLIDER: case DEVICE_BTN_AROUND_SLIDER: case DEVICE_BTN_ABOVE_SLIDER: sendMessage(new MasterVolumeMsg(getState().getActiveZone(), isUp ? MasterVolumeMsg.Command.UP : MasterVolumeMsg.Command.DOWN)); break; case RI_AMP: sendMessage(new AmpOperationCommandMsg(isUp ? AmpOperationCommandMsg.Command.MVLUP.getCode() : AmpOperationCommandMsg.Command.MVLDOWN.getCode())); break; default: // Nothing to do break; } } public void applyShortcut(@NonNull final Context context, @NonNull final CfgFavoriteShortcuts.Shortcut shortcut) { Logging.info(this, "selected favorite shortcut: " + shortcut); final String data = shortcut.toScript(context, state); final MessageScript messageScript = new MessageScript(context, data); activateScript(messageScript); } }
37,646
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
MockupState.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/MockupState.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp; import com.mkulesh.onpc.iscp.messages.AutoPowerMsg; import com.mkulesh.onpc.iscp.messages.DigitalFilterMsg; import com.mkulesh.onpc.iscp.messages.DimmerLevelMsg; import com.mkulesh.onpc.iscp.messages.InputSelectorMsg; import com.mkulesh.onpc.iscp.messages.ListTitleInfoMsg; import com.mkulesh.onpc.iscp.messages.MenuStatusMsg; import com.mkulesh.onpc.iscp.messages.NetworkServiceMsg; import com.mkulesh.onpc.iscp.messages.PlayStatusMsg; import com.mkulesh.onpc.iscp.messages.PowerStatusMsg; import com.mkulesh.onpc.iscp.messages.ReceiverInformationMsg; import com.mkulesh.onpc.iscp.messages.ServiceType; import com.mkulesh.onpc.utils.Logging; class MockupState extends State { MockupState(int zone) { super(ConnectionIf.ProtoType.ISCP, "192.168.1.10", ConnectionIf.ISCP_PORT, zone); Logging.info(this, "Used mockup state"); //Common powerStatus = PowerStatusMsg.PowerStatus.ON; deviceProperties.put("brand", "Onkyo"); deviceProperties.put("model", "NS-6130"); deviceProperties.put("year", "2016"); deviceProperties.put("friendlyname", "PROP_NAME"); deviceProperties.put("firmwareversion", "1234-5678-910"); friendlyName = "FRI_NAME"; networkServices.put("04", new ReceiverInformationMsg.NetworkService("04", "Pandora", 1, false, false)); networkServices.put("0A", new ReceiverInformationMsg.NetworkService("0A", "Spotify", 1, false, false)); networkServices.put("0E", new ReceiverInformationMsg.NetworkService("0E", "TuneIn", 1, false, false)); networkServices.put("12", new ReceiverInformationMsg.NetworkService("12", "Deezer", 1, false, false)); networkServices.put("18", new ReceiverInformationMsg.NetworkService("18", "Airplay", 1, false, false)); networkServices.put("1B", new ReceiverInformationMsg.NetworkService("1B", "Tidal", 1, false, false)); networkServices.put("1D", new ReceiverInformationMsg.NetworkService("1D", "Play Queue", 1, false, false)); inputType = InputSelectorMsg.InputType.NET; dimmerLevel = DimmerLevelMsg.Level.DIM; digitalFilter = DigitalFilterMsg.Filter.F01; autoPower = AutoPowerMsg.Status.ON; // Track info cover = null; album = "Album"; artist = "Artist"; title = "Long title of song"; currentTime = "00:00:59"; maxTime = "00:10:15"; currentTrack = 1; maxTrack = 10; fileFormat = "FLAC/44hHz/16b"; // Playback playStatus = PlayStatusMsg.PlayStatus.PLAY; repeatStatus = PlayStatusMsg.RepeatStatus.ALL; shuffleStatus = PlayStatusMsg.ShuffleStatus.ALL; timeSeek = MenuStatusMsg.TimeSeek.ENABLE; // Navigation serviceType = ServiceType.NET; layerInfo = ListTitleInfoMsg.LayerInfo.NET_TOP; numberOfLayers = 0; numberOfItems = 9; titleBar = "Net"; serviceItems.add(new NetworkServiceMsg(ServiceType.MUSIC_SERVER)); serviceItems.add(new NetworkServiceMsg(ServiceType.SPOTIFY)); serviceItems.add(new NetworkServiceMsg(ServiceType.TUNEIN_RADIO)); serviceItems.add(new NetworkServiceMsg(ServiceType.DEEZER)); serviceItems.add(new NetworkServiceMsg(ServiceType.AIRPLAY)); serviceItems.add(new NetworkServiceMsg(ServiceType.TIDAL)); serviceItems.add(new NetworkServiceMsg(ServiceType.CHROMECAST)); serviceItems.add(new NetworkServiceMsg(ServiceType.FLARECONNECT)); serviceItems.add(new NetworkServiceMsg(ServiceType.PLAYQUEUE)); } }
4,285
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
MessageChannel.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/MessageChannel.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp; import androidx.annotation.NonNull; public interface MessageChannel extends ConnectionIf { int QUEUE_SIZE = 4 * 1024; void start(); void stop(); boolean isActive(); void addAllowedMessage(final String code); ProtoType getProtoType(); boolean connectToServer(@NonNull String host, int port); void sendMessage(EISCPMessage eiscpMessage); }
1,083
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
EISCPMessage.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/EISCPMessage.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp; import com.mkulesh.onpc.utils.Utils; import java.nio.ByteBuffer; import java.util.Arrays; import androidx.annotation.NonNull; public class EISCPMessage { private final static String MSG_START = "ISCP"; private final static String INVALID_MSG = "INVALID"; public final static int CR = 0x0D; public final static int LF = 0x0A; private final static int EOF = 0x1A; private final static Character START_CHAR = '!'; private final static int MIN_MSG_LENGTH = 22; public final static String QUERY = "QSTN"; final static int LOG_LINE_LENGTH = 160; private final int messageId; private final int headerSize, dataSize, version; private final Character modelCategoryId; private final String code; private final String parameters; public EISCPMessage(int messageId, byte[] bytes, int startIndex, int headerSize, int dataSize) throws Exception { this.messageId = messageId; this.headerSize = headerSize; this.dataSize = dataSize; version = getVersion(bytes, startIndex); final String body = getRawMessage(bytes, startIndex); if (body.length() < 5) { throw new Exception("Can not decode message body: length " + body.length() + " is invalid"); } if (body.charAt(0) != START_CHAR) { throw new Exception("Can not find start character in the raw message"); } modelCategoryId = body.charAt(1); code = body.substring(2, 5); parameters = (body.length() > 5) ? body.substring(5) : ""; } public EISCPMessage(final Character modelCategoryId, final String code, final String parameters) { messageId = 0; headerSize = 16; dataSize = 2 + code.length() + parameters.length() + 1; version = 1; this.modelCategoryId = modelCategoryId; this.code = code; this.parameters = parameters; } public EISCPMessage(final String code, final String parameters) { this('1', code, parameters); } @NonNull @Override public String toString() { String res = MSG_START + "/v" + version + "[" + headerSize + "," + dataSize + "]: " + code + "("; if (isMultiline()) { float ln = (float) parameters.length() / (float) LOG_LINE_LENGTH; res += (int) Math.ceil(ln); res += " lines)"; } else { res += parameters; res += ")"; } return res; } private boolean isMultiline() { return parameters.length() > LOG_LINE_LENGTH; } int getMsgSize() { return headerSize + dataSize; } int getMessageId() { return messageId; } Character getModelCategoryId() { return modelCategoryId; } public String getCode() { return code; } String getParameters() { return parameters; } static int getMsgStartIndex(byte[] bytes) { if (bytes.length < MSG_START.length()) { return -1; } for (int i = 0; i < bytes.length; i++) { if (bytes[i] == MSG_START.charAt(0) && bytes[i + 1] == MSG_START.charAt(1) && bytes[i + 2] == MSG_START.charAt(2) && bytes[i + 3] == MSG_START.charAt(3)) { return i; } } return -1; } static int getHeaderSize(byte[] bytes, int startIndex) throws Exception { // Header Size : 4 bytes after "ISCP" if (startIndex + MSG_START.length() + 4 <= bytes.length) { try { return ByteBuffer.wrap(bytes, startIndex + MSG_START.length(), 4).getInt(); } catch (Exception e) { throw new Exception("Can not decode header size: " + e.getLocalizedMessage()); } } return -1; } static int getDataSize(byte[] bytes, int startIndex) throws Exception { // Data Size : 4 bytes after Header Size if (startIndex + MSG_START.length() + 8 <= bytes.length) { try { return ByteBuffer.wrap(bytes, startIndex + MSG_START.length() + 4, 4).getInt(); } catch (Exception e) { throw new Exception("Can not decode data size: " + e.getLocalizedMessage()); } } return -1; } private int getVersion(byte[] bytes, int startIndex) throws Exception { // Version : 1 byte after Data Size try { if (startIndex + MSG_START.length() + 9 <= bytes.length) { final byte[] intBytes = new byte[]{ 0, 0, 0, 0 }; intBytes[3] = bytes[startIndex + MSG_START.length() + 8]; return ByteBuffer.wrap(intBytes).getInt(); } } catch (Exception e) { throw new Exception("Can not decode version: " + e.getLocalizedMessage()); } return -1; } private boolean isSpecialCharacter(byte val) { return val == EOF || val == CR || val == LF; } private String getRawMessage(byte[] bytes, int startIndex) throws Exception { try { if (headerSize > 0 && dataSize > 0 && startIndex + headerSize + dataSize <= bytes.length) { int actualLength = 0; for (int i = 0; i < dataSize; i++) { byte val = bytes[startIndex + headerSize + i]; if (isSpecialCharacter(val)) { break; } actualLength++; } final byte[] stringBytes = Utils.catBuffer(bytes, startIndex + headerSize, actualLength); return new String(stringBytes, Utils.UTF_8); } } catch (Exception e) { throw new Exception("Can not decode raw message: " + e.getLocalizedMessage()); } return INVALID_MSG; } byte[] getBytes() { byte[] parametersBin = parameters.getBytes(Utils.UTF_8); int dSize = 2 + code.length() + parametersBin.length + 1; if (headerSize + dSize < MIN_MSG_LENGTH) { return null; } final byte[] bytes = new byte[headerSize + dSize]; Arrays.fill(bytes, (byte) 0); // Message header for (int i = 0; i < MSG_START.length(); i++) { bytes[i] = (byte) MSG_START.charAt(i); } // Header size byte[] size = ByteBuffer.allocate(4).putInt(headerSize).array(); System.arraycopy(size, 0, bytes, 4, size.length); // Data size size = ByteBuffer.allocate(4).putInt(dSize).array(); System.arraycopy(size, 0, bytes, 8, size.length); // Version bytes[12] = (byte) version; // CMD bytes[16] = (byte) START_CHAR.charValue(); bytes[17] = (byte) modelCategoryId.charValue(); for (int i = 0; i < code.length(); i++) { bytes[i + 18] = (byte) code.charAt(i); } // Parameters System.arraycopy(parametersBin, 0, bytes, 21, parametersBin.length); // End char bytes[21 + parametersBin.length] = (byte) LF; return bytes; } public boolean isQuery() { return getParameters().equalsIgnoreCase(EISCPMessage.QUERY); } }
8,341
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
DcpMediaItemMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/DcpMediaItemMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.jayway.jsonpath.JsonPath; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /* * Denon control protocol - media item * Get Now Playing Media Command: heos://player/get_now_playing_media?pid=player_id */ public class DcpMediaItemMsg extends ISCPMessage { public final static String CODE = "D06"; private final int sid; DcpMediaItemMsg(EISCPMessage raw) throws Exception { super(raw); sid = -1; } DcpMediaItemMsg(final String mid, final int sid) { super(0, mid); this.sid = sid; } public int getSid() { return sid; } @NonNull @Override public String toString() { return CODE + "[" + data + ", SID=" + sid + "]"; } /* * Denon control protocol */ private final static String HEOS_COMMAND = "player/get_now_playing_media"; @Nullable public static DcpMediaItemMsg processHeosMessage(@NonNull final String command, @NonNull final String heosMsg) { if (HEOS_COMMAND.equals(command)) { final String type = JsonPath.read(heosMsg, "$.payload.type"); final String mid; if ("station".equals(type)) { mid = JsonPath.read(heosMsg, "$.payload.album_id"); } else { mid = JsonPath.read(heosMsg, "$.payload.mid"); } final int sid = JsonPath.read(heosMsg, "$.payload.sid"); return new DcpMediaItemMsg(mid, sid); } return null; } @Nullable @Override public String buildDcpMsg(boolean isQuery) { if (isQuery) { return "heos://" + HEOS_COMMAND + "?pid=" + DCP_HEOS_PID; } return null; } }
2,606
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
MasterVolumeMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/MasterVolumeMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ZonedMessage; import com.mkulesh.onpc.utils.Logging; import com.mkulesh.onpc.utils.Utils; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; /* * Master Volume Command */ public class MasterVolumeMsg extends ZonedMessage { final static String CODE = "MVL"; final static String ZONE2_CODE = "ZVL"; final static String ZONE3_CODE = "VL3"; final static String ZONE4_CODE = "VL4"; public final static String[] ZONE_COMMANDS = new String[]{ CODE, ZONE2_CODE, ZONE3_CODE, ZONE4_CODE }; public final static int NO_LEVEL = -1; public static final int MAX_VOLUME_1_STEP = 0x64; @SuppressWarnings("unused") public enum Command implements DcpStringParameterIf { UP("UP", R.string.master_volume_up, R.drawable.volume_amp_up), DOWN("DOWN", R.string.master_volume_down, R.drawable.volume_amp_down), UP1("N/A", R.string.master_volume_up1, R.drawable.volume_amp_up), DOWN1("N/A", R.string.master_volume_down1, R.drawable.volume_amp_down); final String dcpCode; @StringRes final int descriptionId; @DrawableRes final int imageId; Command(final String dcpCode, @StringRes final int descriptionId, @DrawableRes final int imageId) { this.dcpCode = dcpCode; this.descriptionId = descriptionId; this.imageId = imageId; } public String getCode() { return toString(); } @NonNull public String getDcpCode() { return dcpCode; } @StringRes public int getDescriptionId() { return descriptionId; } @DrawableRes public int getImageId() { return imageId; } } private Command command; private int volumeLevel = NO_LEVEL; MasterVolumeMsg(EISCPMessage raw) throws Exception { super(raw, ZONE_COMMANDS); try { volumeLevel = Integer.parseInt(data, 16); command = null; } catch (Exception e) { command = (Command) searchParameter(data, Command.values(), Command.UP); } } public MasterVolumeMsg(int zoneIndex, Command level) { super(0, null, zoneIndex); this.command = level; this.volumeLevel = NO_LEVEL; } public MasterVolumeMsg(int zoneIndex, int volumeLevel) { super(0, null, zoneIndex); this.command = null; this.volumeLevel = volumeLevel; } @Override public String getZoneCommand() { return ZONE_COMMANDS[zoneIndex]; } public int getVolumeLevel() { return volumeLevel; } @NonNull @Override public String toString() { return getZoneCommand() + "[" + data + "; ZONE_INDEX=" + zoneIndex + "; LEVEL=" + volumeLevel + "; CMD=" + (command != null ? command.toString() : "null") + "]"; } @Override public EISCPMessage getCmdMsg() { String par = ""; if (command != null) { par = command.getCode(); } else if (volumeLevel != NO_LEVEL) { par = String.format("%02x", volumeLevel); } return new EISCPMessage(getZoneCommand(), par); } @Override public boolean hasImpactOnMediaList() { return false; } /* * Denon control protocol */ private final static String[] DCP_COMMANDS = new String[]{ "MV", "Z2", "Z3" }; @NonNull public static ArrayList<String> getAcceptedDcpCodes() { return new ArrayList<>(Arrays.asList(DCP_COMMANDS)); } public static MasterVolumeMsg processDcpMessage(@NonNull String dcpMsg) { for (int i = 0; i < DCP_COMMANDS.length; i++) { if (dcpMsg.startsWith(DCP_COMMANDS[i]) && !dcpMsg.contains("MAX")) { final String par = dcpMsg.substring(DCP_COMMANDS[i].length()).trim(); try { float volumeLevel = Integer.parseInt(par); int volumeLevelInt = i == 0 ? scaleValueMainZone(volumeLevel, par) : scaleValueExtZone(volumeLevel); return new MasterVolumeMsg(i, volumeLevelInt); } catch (Exception e) { Logging.info(MasterVolumeMsg.class, "Unable to parse volume level " + par); return null; } } } return null; } @Nullable @Override public String buildDcpMsg(boolean isQuery) { if (isQuery) { return DCP_COMMANDS[0] + DCP_MSG_REQ; } else if (zoneIndex < DCP_COMMANDS.length) { if (command != null) { return DCP_COMMANDS[zoneIndex] + command.getDcpCode(); } else if (volumeLevel != NO_LEVEL) { final String par = zoneIndex == 0 ? getValueMainZone() : getValueExtZone(); if (!par.isEmpty()) { return DCP_COMMANDS[zoneIndex] + par; } } } return null; } private static int scaleValueMainZone(float volumeLevel, String par) { if (par.length() > 2) { volumeLevel = volumeLevel / 10; } return (int) (2.0 * volumeLevel); } private String getValueMainZone() { final float f = 10.0f * ((float) volumeLevel / 2.0f); final DecimalFormat df = Utils.getDecimalFormat("000"); final String fullStr = df.format(f); return fullStr.endsWith("0") ? fullStr.substring(0, 2) : (fullStr.endsWith("5") ? fullStr : ""); } private static int scaleValueExtZone(float volumeLevel) { return (int) volumeLevel; } private String getValueExtZone() { final float f = (float) volumeLevel; final DecimalFormat df = Utils.getDecimalFormat("00"); return df.format(f); } }
7,184
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
DcpMediaEventMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/DcpMediaEventMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /* * Denon control protocol: * Player Queue Changed Event * { * "heos": { * "command": " event/player_queue_changed", * "message": "pid='player_id'" * } * } */ public class DcpMediaEventMsg extends ISCPMessage { public final static String CODE = "D07"; DcpMediaEventMsg(final String event) { super(0, event); } @NonNull @Override public String toString() { return CODE + "[" + data + "]"; } /* * Denon control protocol */ public final static String HEOS_EVENT_QUEUE = "event/player_queue_changed"; public final static String HEOS_EVENT_SERVICEOPT = "browse/set_service_option"; @Nullable public static DcpMediaEventMsg processHeosMessage(@NonNull final String command) { if (HEOS_EVENT_QUEUE.equals(command) || HEOS_EVENT_SERVICEOPT.equals(command)) { return new DcpMediaEventMsg(command); } return null; } }
1,795
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
MessageFactory.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/MessageFactory.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; /** * A static helper class used to create messages */ public class MessageFactory { public static ISCPMessage create(EISCPMessage raw) throws Exception { switch (raw.getCode().toUpperCase()) { case PowerStatusMsg.CODE: case PowerStatusMsg.ZONE2_CODE: case PowerStatusMsg.ZONE3_CODE: case PowerStatusMsg.ZONE4_CODE: return new PowerStatusMsg(raw); case FirmwareUpdateMsg.CODE: return new FirmwareUpdateMsg(raw); case ReceiverInformationMsg.CODE: return new ReceiverInformationMsg(raw); case FriendlyNameMsg.CODE: return new FriendlyNameMsg(raw); case DeviceNameMsg.CODE: return new DeviceNameMsg(raw); case InputSelectorMsg.CODE: case InputSelectorMsg.ZONE2_CODE: case InputSelectorMsg.ZONE3_CODE: case InputSelectorMsg.ZONE4_CODE: return new InputSelectorMsg(raw); case TimeInfoMsg.CODE: return new TimeInfoMsg(raw); case JacketArtMsg.CODE: return new JacketArtMsg(raw); case TitleNameMsg.CODE: return new TitleNameMsg(raw); case AlbumNameMsg.CODE: return new AlbumNameMsg(raw); case ArtistNameMsg.CODE: return new ArtistNameMsg(raw); case FileFormatMsg.CODE: return new FileFormatMsg(raw); case TrackInfoMsg.CODE: return new TrackInfoMsg(raw); case PlayStatusMsg.CODE: case PlayStatusMsg.CD_CODE: return new PlayStatusMsg(raw); case ListTitleInfoMsg.CODE: return new ListTitleInfoMsg(raw); case ListInfoMsg.CODE: return new ListInfoMsg(raw); case ListItemInfoMsg.CODE: return new ListItemInfoMsg(raw); case MenuStatusMsg.CODE: return new MenuStatusMsg(raw); case XmlListInfoMsg.CODE: return new XmlListInfoMsg(raw); case DisplayModeMsg.CODE: return new DisplayModeMsg(raw); case DimmerLevelMsg.CODE: return new DimmerLevelMsg(raw); case DigitalFilterMsg.CODE: return new DigitalFilterMsg(raw); case AudioMutingMsg.CODE: case AudioMutingMsg.ZONE2_CODE: case AudioMutingMsg.ZONE3_CODE: case AudioMutingMsg.ZONE4_CODE: return new AudioMutingMsg(raw); case MasterVolumeMsg.CODE: case MasterVolumeMsg.ZONE2_CODE: case MasterVolumeMsg.ZONE3_CODE: case MasterVolumeMsg.ZONE4_CODE: return new MasterVolumeMsg(raw); case ToneCommandMsg.CODE: case ToneCommandMsg.ZONE2_CODE: case ToneCommandMsg.ZONE3_CODE: return new ToneCommandMsg(raw); case SubwooferLevelCommandMsg.CODE: return new SubwooferLevelCommandMsg(raw); case CenterLevelCommandMsg.CODE: return new CenterLevelCommandMsg(raw); case PresetCommandMsg.CODE: case PresetCommandMsg.ZONE2_CODE: case PresetCommandMsg.ZONE3_CODE: case PresetCommandMsg.ZONE4_CODE: return new PresetCommandMsg(raw); case PresetMemoryMsg.CODE: return new PresetMemoryMsg(raw); case RadioStationNameMsg.CODE: return new RadioStationNameMsg(raw); case TuningCommandMsg.CODE: case TuningCommandMsg.ZONE2_CODE: case TuningCommandMsg.ZONE3_CODE: case TuningCommandMsg.ZONE4_CODE: return new TuningCommandMsg(raw); case RDSInformationMsg.CODE: return new RDSInformationMsg(raw); case MusicOptimizerMsg.CODE: return new MusicOptimizerMsg(raw); case AutoPowerMsg.CODE: return new AutoPowerMsg(raw); case CustomPopupMsg.CODE: return new CustomPopupMsg(raw); case GoogleCastVersionMsg.CODE: return new GoogleCastVersionMsg(raw); case GoogleCastAnalyticsMsg.CODE: return new GoogleCastAnalyticsMsg(raw); case ListeningModeMsg.CODE: return new ListeningModeMsg(raw); case HdmiCecMsg.CODE: return new HdmiCecMsg(raw); case DirectCommandMsg.CODE: return new DirectCommandMsg(raw); case PhaseMatchingBassMsg.CODE: return new PhaseMatchingBassMsg(raw); case SleepSetCommandMsg.CODE: return new SleepSetCommandMsg(raw); case SpeakerACommandMsg.CODE: case SpeakerACommandMsg.ZONE2_CODE: return new SpeakerACommandMsg(raw); case SpeakerBCommandMsg.CODE: case SpeakerBCommandMsg.ZONE2_CODE: return new SpeakerBCommandMsg(raw); case LateNightCommandMsg.CODE: return new LateNightCommandMsg(raw); case NetworkStandByMsg.CODE: return new NetworkStandByMsg(raw); case PrivacyPolicyStatusMsg.CODE: return new PrivacyPolicyStatusMsg(raw); case CdPlayerOperationCommandMsg.CODE: return new CdPlayerOperationCommandMsg(raw); case MultiroomDeviceInformationMsg.CODE: return new MultiroomDeviceInformationMsg(raw); case MultiroomChannelSettingMsg.CODE: return new MultiroomChannelSettingMsg(raw); case AudioInformationMsg.CODE: return new AudioInformationMsg(raw); case VideoInformationMsg.CODE: return new VideoInformationMsg(raw); default: throw new Exception("No factory method for message " + raw.getCode()); } } }
6,399
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
NetworkServiceMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/NetworkServiceMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /* * Select Network Service directly only when NET selector is selected. */ public class NetworkServiceMsg extends ISCPMessage { public final static String CODE = "NSV"; private final ServiceType service; NetworkServiceMsg(EISCPMessage raw) throws Exception { super(raw); final String cd = data.substring(0, data.length() - 1); this.service = (ServiceType) searchDcpParameter(cd, ServiceType.values(), ServiceType.UNKNOWN); } public NetworkServiceMsg(@NonNull final ServiceType service) { super(0, null); this.service = service; } public NetworkServiceMsg(@NonNull final String name) { super(0, null); this.service = searchByName(name); } public NetworkServiceMsg(NetworkServiceMsg other) { super(other); service = other.service; } public ServiceType getService() { return service; } @NonNull @Override public String toString() { return CODE + "[" + service.toString() + "/" + service.getCode() + "]"; } @Override public EISCPMessage getCmdMsg() { final String param = service.getCode() + "0"; return new EISCPMessage(CODE, param); } private ServiceType searchByName(@NonNull final String name) { for (ServiceType t : ServiceType.values()) { if (t.getName().equalsIgnoreCase(name)) { return t; } } return ServiceType.UNKNOWN; } /* * Denon control protocol */ private final static String HEOS_COMMAND = "browse/browse"; @Nullable @Override public String buildDcpMsg(boolean isQuery) { if (service == ServiceType.DCP_PLAYQUEUE) { return "heos://player/get_queue?pid=" + DCP_HEOS_PID + "&range=0,9999"; } if (service != null) { return "heos://" + HEOS_COMMAND + "?sid=" + service.getDcpCode().substring(2); } return null; } }
2,935
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
DeviceNameMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/DeviceNameMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; /* * NET/USB Device Name */ class DeviceNameMsg extends ISCPMessage { public final static String CODE = "NDN"; DeviceNameMsg(EISCPMessage raw) throws Exception { super(raw); } @NonNull @Override public String toString() { return CODE + "[" + data + "]"; } }
1,151
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
TitleNameMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/TitleNameMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.jayway.jsonpath.JsonPath; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /* * NET/USB Title Name (variable-length, 64 ASCII letters max) */ public class TitleNameMsg extends ISCPMessage { public final static String CODE = "NTI"; TitleNameMsg(EISCPMessage raw) throws Exception { super(raw); } TitleNameMsg(final String name) { super(0, name); } @NonNull @Override public String toString() { return CODE + "[" + data + "]"; } /* * Denon control protocol */ private final static String HEOS_COMMAND = "player/get_now_playing_media"; @Nullable public static TitleNameMsg processHeosMessage(@NonNull final String command, @NonNull final String heosMsg) { if (HEOS_COMMAND.equals(command)) { final String name = JsonPath.read(heosMsg, "$.payload.song"); return new TitleNameMsg(name); } return null; } }
1,806
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
RadioStationNameMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/RadioStationNameMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import java.util.ArrayList; import java.util.Arrays; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /* * DAB/FM Station Name (UTF-8) */ public class RadioStationNameMsg extends ISCPMessage { public final static String CODE = "DSN"; private final DcpTunerModeMsg.TunerMode dcpTunerMode; RadioStationNameMsg(EISCPMessage raw) throws Exception { super(raw); // For ISCP, station name is only available for DAB this.dcpTunerMode = DcpTunerModeMsg.TunerMode.DAB; } RadioStationNameMsg(String name, @NonNull DcpTunerModeMsg.TunerMode dcpTunerMode) { super(0, name); this.dcpTunerMode = dcpTunerMode; } @NonNull @Override public String toString() { return CODE + "[" + data + "; MODE=" + dcpTunerMode + "]"; } /* * Denon control protocol */ private final static String DCP_COMMAND_FM = "TFANNAME"; private final static String DCP_COMMAND_DAB = "DA"; private final static String DCP_COMMAND_DAB_EXT = "STN"; @NonNull public static ArrayList<String> getAcceptedDcpCodes() { return new ArrayList<>(Arrays.asList(DCP_COMMAND_FM, DCP_COMMAND_DAB + DCP_COMMAND_DAB_EXT)); } @Nullable public static RadioStationNameMsg processDcpMessage(@NonNull String dcpMsg) { if (dcpMsg.startsWith(DCP_COMMAND_FM)) { final String par = dcpMsg.substring(DCP_COMMAND_FM.length()).trim(); return new RadioStationNameMsg(par, DcpTunerModeMsg.TunerMode.FM); } if (dcpMsg.startsWith(DCP_COMMAND_DAB + DCP_COMMAND_DAB_EXT)) { final String par = dcpMsg.substring((DCP_COMMAND_DAB + DCP_COMMAND_DAB_EXT).length()).trim(); return new RadioStationNameMsg(par, DcpTunerModeMsg.TunerMode.DAB); } return null; } @Nullable @Override public String buildDcpMsg(boolean isQuery) { final String fmReq = DCP_COMMAND_FM + DCP_MSG_REQ; final String dabReq = DCP_COMMAND_DAB + " " + DCP_MSG_REQ; return fmReq + DCP_MSG_SEP + dabReq; } @NonNull public DcpTunerModeMsg.TunerMode getDcpTunerMode() { return dcpTunerMode; } }
3,081
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
PowerStatusMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/PowerStatusMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ZonedMessage; import java.util.ArrayList; import java.util.Arrays; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /* * System Power Command */ public class PowerStatusMsg extends ZonedMessage { public final static String CODE = "PWR"; final static String ZONE2_CODE = "ZPW"; final static String ZONE3_CODE = "PW3"; final static String ZONE4_CODE = "PW4"; public final static String[] ZONE_COMMANDS = new String[]{ CODE, ZONE2_CODE, ZONE3_CODE, ZONE4_CODE }; /* * Play Status: "00": System Standby, "01": System On, "ALL": All Zone(including Main Zone) Standby */ public enum PowerStatus implements DcpStringParameterIf { STB("00", "OFF"), ON("01", "ON"), ALL_STB("ALL", "STANDBY"), NONE("N/A", "N/A"); final String code, dcpCode; PowerStatus(String code, String dcpCode) { this.code = code; this.dcpCode = dcpCode; } public String getCode() { return code; } @NonNull public String getDcpCode() { return dcpCode; } } private PowerStatus powerStatus = PowerStatus.NONE; PowerStatusMsg(EISCPMessage raw) throws Exception { super(raw, ZONE_COMMANDS); powerStatus = (PowerStatus) searchParameter(data, PowerStatus.values(), powerStatus); } public PowerStatusMsg(int zoneIndex, PowerStatus powerStatus) { super(0, null, zoneIndex); this.powerStatus = powerStatus; } @Override public String getZoneCommand() { return ZONE_COMMANDS[zoneIndex]; } public PowerStatus getPowerStatus() { return powerStatus; } @NonNull @Override public String toString() { return getZoneCommand() + "[" + data + "; ZONE_INDEX=" + zoneIndex + "; PWR=" + powerStatus.toString() + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(getZoneCommand(), powerStatus.getCode()); } /* * Denon control protocol */ private final static String[] DCP_COMMANDS = new String[]{ "ZM", "Z2", "Z3" }; @NonNull public static ArrayList<String> getAcceptedDcpCodes() { return new ArrayList<>(Arrays.asList(DCP_COMMANDS)); } @Nullable public static PowerStatusMsg processDcpMessage(@NonNull String dcpMsg) { for (int i = 0; i < DCP_COMMANDS.length; i++) { final PowerStatus s = (PowerStatus) searchDcpParameter(DCP_COMMANDS[i], dcpMsg, PowerStatus.values()); if (s != null) { return new PowerStatusMsg(i, s); } } return null; } @Nullable @Override public String buildDcpMsg(boolean isQuery) { if (powerStatus == PowerStatus.ALL_STB) { return "PW" + powerStatus.getDcpCode(); } else if (zoneIndex < DCP_COMMANDS.length) { return DCP_COMMANDS[zoneIndex] + (isQuery ? DCP_MSG_REQ : powerStatus.getDcpCode()); } return null; } }
3,989
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
LateNightCommandMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/LateNightCommandMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /* * Late Night Command */ public class LateNightCommandMsg extends ISCPMessage { public final static String CODE = "LTN"; public enum Status implements StringParameterIf { NONE("NONE", R.string.device_late_night_none), DISABLED("N/A", R.string.device_late_night_disabled), OFF("00", R.string.device_late_night_off), LOW("01", R.string.device_late_night_low), HIGH("02", R.string.device_late_night_high), AUTO("03", R.string.device_late_night_auto), UP("UP", R.string.device_late_night_up); final String code; @StringRes final int descriptionId; Status(final String code, @StringRes final int descriptionId) { this.code = code; this.descriptionId = descriptionId; } public String getCode() { return code; } @StringRes public int getDescriptionId() { return descriptionId; } } private final Status status; LateNightCommandMsg(EISCPMessage raw) throws Exception { super(raw); status = (Status) searchParameter(data, Status.values(), Status.DISABLED); } public LateNightCommandMsg(Status level) { super(0, null); this.status = level; } public Status getStatus() { return status; } @NonNull @Override public String toString() { return CODE + "[" + status.toString() + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, status.getCode()); } @Override public boolean hasImpactOnMediaList() { return false; } }
2,631
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
JacketArtMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/JacketArtMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import com.jayway.jsonpath.JsonPath; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import com.mkulesh.onpc.utils.Logging; import com.mkulesh.onpc.utils.Utils; import java.io.ByteArrayOutputStream; import java.net.URL; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /* * NET/USB Jacket Art (When Jacket Art is available and Output for Network Control Only) */ public class JacketArtMsg extends ISCPMessage { public final static String CODE = "NJA"; public final static String TYPE_LINK = "LINK"; public final static String TYPE_BMP = "BMP"; public final static String REQUEST = "REQ"; /* * Image type 0:BMP, 1:JPEG, 2:URL, n:No Image */ public enum ImageType implements CharParameterIf { BMP('0'), JPEG('1'), URL('2'), NO_IMAGE('n'); final Character code; ImageType(Character code) { this.code = code; } public Character getCode() { return code; } } private ImageType imageType = ImageType.NO_IMAGE; /* * Packet flag 0:Start, 1:Next, 2:End, -:not used */ public enum PacketFlag implements CharParameterIf { START('0'), NEXT('1'), END('2'), NOT_USED('-'); final Character code; PacketFlag(Character code) { this.code = code; } public Character getCode() { return code; } } private PacketFlag packetFlag = PacketFlag.NOT_USED; private URL url = null; private byte[] rawData = null; JacketArtMsg(EISCPMessage raw) throws Exception { super(raw); if (data.length() > 0) { imageType = (ImageType) searchParameter(data.charAt(0), ImageType.values(), imageType); } if (data.length() > 1) { packetFlag = (PacketFlag) searchParameter(data.charAt(1), PacketFlag.values(), packetFlag); } if (data.length() > 2) { switch (imageType) { case URL: url = new URL(data.substring(2)); break; case BMP: case JPEG: rawData = convertRaw(data.substring(2)); break; case NO_IMAGE: // nothing to do; break; } } } JacketArtMsg(final String url) throws Exception { super(0, CODE); this.imageType = ImageType.URL; this.url = new URL(url); } public ImageType getImageType() { return imageType; } public PacketFlag getPacketFlag() { return packetFlag; } public byte[] getRawData() { return rawData; } public URL getUrl() { return url; } @NonNull @Override public String toString() { return CODE + "/" + messageId + "[" + data.substring(0, 2) + "..." + "; TYPE=" + imageType.toString() + "; PACKET=" + packetFlag.toString() + "; URL=" + url + "; RAW(" + (rawData == null ? "null" : rawData.length) + ")" + "]"; } private byte[] convertRaw(String str) { byte[] bytes = new byte[str.length() / 2]; for (int i = 0; i < bytes.length; i++) { final int j1 = 2 * i; final int j2 = 2 * i + 1; if (j1 < str.length() && j2 < str.length()) { bytes[i] = (byte) Integer.parseInt(str.substring(j1, j2 + 1), 16); } } return bytes; } public Bitmap loadFromUrl() { Bitmap cover = null; final byte[] bytes = Utils.getUrlData(url, true); if (bytes != null) { final int offset = Utils.getUrlHeaderLength(bytes); final int length = bytes.length - offset; if (length > 0) { Logging.info(this, "Cover image size=" + length); cover = BitmapFactory.decodeByteArray(bytes, offset, length); if (cover == null) { Logging.info(this, "can not open image: BitmapFactory.decodeByteArray error"); } } } return cover; } public Bitmap loadFromBuffer(ByteArrayOutputStream coverBuffer) { if (coverBuffer == null) { Logging.info(this, "can not open image: empty stream"); return null; } Bitmap cover = null; try { Logging.info(this, "loading image from stream"); coverBuffer.flush(); coverBuffer.close(); final byte[] out = coverBuffer.toByteArray(); cover = BitmapFactory.decodeByteArray(out, 0, out.length); } catch (Exception e) { Logging.info(this, "can not open image: " + e.getLocalizedMessage()); } if (cover == null) { Logging.info(this, "can not open image"); } return cover; } /* * Denon control protocol */ private final static String HEOS_COMMAND = "player/get_now_playing_media"; @Nullable public static JacketArtMsg processHeosMessage(@NonNull final String command, @NonNull final String heosMsg) throws Exception { if (HEOS_COMMAND.equals(command)) { final String name = JsonPath.read(heosMsg, "$.payload.image_url"); if (name != null && !name.isEmpty()) { return new JacketArtMsg(name); } } return null; } }
6,522
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
SpeakerACommandMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/SpeakerACommandMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ZonedMessage; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /* * Speaker A Command (For Main zone and Zone 2 only) */ public class SpeakerACommandMsg extends ZonedMessage { final static String CODE = "SPA"; final static String ZONE2_CODE = "ZPA"; public final static String[] ZONE_COMMANDS = new String[]{ CODE, ZONE2_CODE, CODE, CODE }; public enum Status implements StringParameterIf { NONE("N/A", R.string.device_two_way_switch_none), OFF("00", R.string.device_two_way_switch_off), ON("01", R.string.device_two_way_switch_on), TOGGLE("UP", R.string.speaker_a_command_toggle); /* Only available for main zone */ final String code; @StringRes final int descriptionId; Status(final String code, @StringRes final int descriptionId) { this.code = code; this.descriptionId = descriptionId; } public String getCode() { return code; } @SuppressWarnings("unused") @StringRes public int getDescriptionId() { return descriptionId; } } private final Status status; SpeakerACommandMsg(EISCPMessage raw) throws Exception { super(raw, ZONE_COMMANDS); status = (Status) searchParameter(data, Status.values(), Status.NONE); } public SpeakerACommandMsg(int zoneIndex, Status level) { super(0, null, zoneIndex); this.status = level; } @Override public String getZoneCommand() { return ZONE_COMMANDS[zoneIndex]; } public Status getStatus() { return status; } @NonNull @Override public String toString() { return getZoneCommand() + "[" + data + "; ZONE_INDEX=" + zoneIndex + "; STATUS=" + status.toString() + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(getZoneCommand(), status.getCode()); } @Override public boolean hasImpactOnMediaList() { return false; } }
2,961
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
ServiceType.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/ServiceType.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /* * Service icon * "00":Music Server (DLNA), "01":My Favorite, "02":vTuner, * "03":SiriusXM, "04":Pandora, * "05":Rhapsody, "06":Last.fm, "07":Napster, "08":Slacker, "09":Mediafly, * "0A":Spotify, "0B":AUPEO!, * "0C":radiko, "0D":e-onkyo, "0E":TuneIn, "0F":MP3tunes, "10":Simfy, * "11":Home Media, "12":Deezer, "13":iHeartRadio, "18":Airplay, * “1A”: onkyo Music, “1B”:TIDAL, "1D":PlayQueue, * “40”:Chromecast built-in, “41”:FireConnect, "42":Play-Fi, * "F0": USB/USB(Front), "F1: USB(Rear), "F2":Internet Radio * "F3":NET, "F4":Bluetooth */ public enum ServiceType implements ISCPMessage.DcpStringParameterIf { // Integra // Note: some names are device-specific, see comments // We use the names when ListInfoMsg is processed as a fallback is no ReceiverInformationMsg // exists for given device UNKNOWN("XX", "", R.string.dashed_string), MUSIC_SERVER("00", "DLNA", R.string.service_music_server, R.drawable.media_item_media_server), // TX-8050 FAVORITE("01", "My Favorites", R.string.service_favorite, R.drawable.media_item_favorite), // TX-8050 VTUNER("02", "vTuner Internet Radio", R.string.service_vtuner), // TX-8050 SIRIUSXM("03", "SiriusXM Internet Radio", R.string.service_siriusxm), // TX-8050 PANDORA("04", "Pandora Internet Radio", R.string.service_pandora, R.drawable.media_item_pandora), // TX-NR616 RHAPSODY("05", "Rhapsody", R.string.service_rhapsody), // TX-NR616 LAST_FM("06", "Last.fm Internet Radio", R.string.service_last, R.drawable.media_item_lastfm), // TX-8050, TX-NR616 NAPSTER("07", "Napster", R.string.service_napster, R.drawable.media_item_napster), SLACKER("08", "Slacker Personal Radio", R.string.service_slacker), // TX-NR616 MEDIAFLY("09", "Mediafly", R.string.service_mediafly), SPOTIFY("0A", "Spotify", R.string.service_spotify, R.drawable.media_item_spotify), // TX-NR616 AUPEO("0B", "AUPEO! PERSONAL RADIO", R.string.service_aupeo), // TX-8050, TX-NR616 RADIKO("0C", "Radiko", R.string.service_radiko), E_ONKYO("0D", "e-onkyo", R.string.service_e_onkyo), TUNEIN_RADIO("0E", "TuneIn", R.string.service_tunein_radio, R.drawable.media_item_tunein), MP3TUNES("0F", "mp3tunes", R.string.service_mp3tunes), // TX-NR616 SIMFY("10", "Simfy", R.string.service_simfy), HOME_MEDIA("11", "Home Media", R.string.service_home_media, R.drawable.media_item_media_server), // TX-NR616 DEEZER("12", "Deezer", R.string.service_deezer, R.drawable.media_item_deezer), IHEARTRADIO("13", "iHeartRadio", R.string.service_iheartradio), AIRPLAY("18", "Airplay", R.string.service_airplay, R.drawable.media_item_airplay), ONKYO_MUSIC("1A", "onkyo music", R.string.service_onkyo_music), TIDAL("1B", "Tidal", R.string.service_tidal, R.drawable.media_item_tidal), AMAZON_MUSIC("1C", "AmazonMusic", R.string.service_amazon_music, R.drawable.media_item_amazon), PLAYQUEUE("1D", "Play Queue", R.string.service_playqueue, R.drawable.media_item_playqueue), CHROMECAST("40", "Chromecast built-in", R.string.service_chromecast, R.drawable.media_item_chromecast), FIRECONNECT("41", "FireConnect", R.string.service_fireconnect), PLAY_FI("42", "DTS Play-Fi", R.string.service_play_fi, R.drawable.media_item_play_fi), FLARECONNECT("43", "FlareConnect", R.string.service_flareconnect, R.drawable.media_item_flare_connect), AIRPLAY1("44", "Airplay", R.string.service_airplay, R.drawable.media_item_airplay), // TX-RZ630 uses code "44" for Airplay instead of "18" USB_FRONT("F0", "USB(Front)", R.string.service_usb_front, R.drawable.media_item_usb), USB_REAR("F1", "USB(Rear)", R.string.service_usb_rear, R.drawable.media_item_usb), INTERNET_RADIO("F2", "Internet radio", R.string.service_internet_radio, R.drawable.media_item_radio_digital), NET("F3", "NET", R.string.service_net, R.drawable.media_item_net), BLUETOOTH("F4", "Bluetooth", R.string.service_bluetooth, R.drawable.media_item_bluetooth), // Denon DCP_PANDORA("HS1", "Pandora", R.string.service_pandora, R.drawable.media_item_pandora), DCP_RHAPSODY("HS2", "Rhapsody", R.string.service_rhapsody), DCP_TUNEIN("HS3", "TuneIn", R.string.service_tunein_radio, R.drawable.media_item_tunein), DCP_SPOTIFY("HS4", "Spotify", R.string.service_spotify, R.drawable.media_item_spotify), DCP_DEEZER("HS5", "Deezer", R.string.service_deezer, R.drawable.media_item_deezer), DCP_NAPSTER("HS6", "Napster", R.string.service_napster, R.drawable.media_item_napster), DCP_IHEARTRADIO("HS7", "iHeartRadio", R.string.service_iheartradio), DCP_SIRIUSXM("HS8", "Sirius XM", R.string.service_siriusxm), DCP_SOUNDCLOUD("HS9", "Soundcloud", R.string.service_soundcloud, R.drawable.media_item_soundcloud), DCP_TIDAL("HS10", "Tidal", R.string.service_tidal, R.drawable.media_item_tidal), DCP_AMAZON_MUSIC("HS13", "Amazon Music", R.string.service_amazon_music, R.drawable.media_item_amazon), DCP_LOCAL("HS1024", "Local Music", R.string.service_local_music, R.drawable.media_item_folder), DCP_PLAYLIST("HS1025", "Playlists", R.string.service_playlist, R.drawable.media_item_playqueue), DCP_HISTORY("HS1026", "History", R.string.service_history, R.drawable.media_item_history), DCP_AUX("HS1027", "AUX Input", R.string.service_aux_input, R.drawable.media_item_aux), DCP_FAVORITE("HS1028", "Favorites", R.string.service_favorite, R.drawable.media_item_favorite), DCP_PLAYQUEUE("HS9999", "Play Queue", R.string.service_playqueue, R.drawable.media_item_playqueue); private final String code; private final String name; @StringRes private final int descriptionId; @DrawableRes private final int imageId; ServiceType(final String code, final String name, @StringRes final int descriptionId, @DrawableRes final int imageId) { this.code = code; this.name = name; this.descriptionId = descriptionId; this.imageId = imageId; } ServiceType(final String code, final String name, @StringRes final int descriptionId) { this.code = code; this.name = name; this.descriptionId = descriptionId; this.imageId = R.drawable.media_item_unknown; } public String getCode() { return code; } @NonNull @Override public String getDcpCode() { return code.startsWith("HS") ? code : "N/A"; } public String getName() { return name; } @StringRes public int getDescriptionId() { return descriptionId; } @DrawableRes public int getImageId() { return imageId; } }
7,548
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
DcpMediaContainerMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/DcpMediaContainerMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import android.annotation.SuppressLint; import com.jayway.jsonpath.JsonPath; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import com.mkulesh.onpc.utils.Logging; import com.mkulesh.onpc.utils.Utils; import net.minidev.json.JSONArray; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /* * Denon control protocol - media container */ public class DcpMediaContainerMsg extends ISCPMessage { public enum BrowseType { MEDIA_LIST, PLAY_QUEUE, SEARCH_RESULT, MEDIA_ITEM, PLAYQUEUE_ITEM } public final static String CODE = "D05"; private final static String EMPTY = ""; private final static String YES = "yes"; public final static int SO_ADD_TO_HEOS = 19; public final static int SO_REMOVE_FROM_HEOS = 20; public final static int SO_CONTAINER = 21; public final static int SO_ADD_AND_PLAY_ALL = 201; public final static int SO_ADD_ALL = 203; public final static int SO_REPLACE_AND_PLAY_ALL = 204; private final BrowseType browseType; private String sid; private final String parentSid; private final String cid; private final String parentCid; private String mid = EMPTY; private String type = EMPTY; private final boolean container; private boolean playable = false; private String name = EMPTY; private String artist = EMPTY; private String album = EMPTY; private String imageUrl = EMPTY; private int start = 0; private int count = 0; private String aid = EMPTY; private String qid = EMPTY; private ListTitleInfoMsg.LayerInfo layerInfo = null; private String scid = EMPTY; private String searchStr = EMPTY; private final List<XmlListItemMsg> items = new ArrayList<>(); private final List<XmlListItemMsg> options = new ArrayList<>(); private final static String HEOS_RESP_BROWSE_SERV = "heos/browse"; private final static String HEOS_RESP_BROWSE_CONT = "browse/browse"; private final static String HEOS_RESP_BROWSE_SEARCH = "browse/search"; private final static String HEOS_RESP_BROWSE_QUEUE = "player/get_queue"; public final static String HEOS_SET_SERVICE_OPTION = "browse/set_service_option"; DcpMediaContainerMsg(EISCPMessage raw) throws Exception { super(raw); final String browseTypeStr = getElement(data, "$.item.browseType"); this.browseType = BrowseType.values()[Integer.parseInt(browseTypeStr)]; this.sid = getElement(data, "$.item.sid"); this.parentSid = getElement(data, "$.item.parentSid"); this.cid = getElement(data, "$.item.cid"); this.parentCid = getElement(data, "$.item.parentCid"); this.mid = getElement(data, "$.item.mid"); this.type = getElement(data, "$.item.type"); final String startStr = getElement(data, "$.item.start"); if (!startStr.isEmpty() && Utils.isInteger(startStr)) { this.start = Integer.parseInt(startStr); } this.container = YES.equalsIgnoreCase(getElement(data, "$.item.container")); this.playable = YES.equalsIgnoreCase(getElement(data, "$.item.playable")); this.name = getElement(data, "$.item.name"); this.aid = getElement(data, "$.item.aid"); this.qid = getElement(data, "$.item.qid"); this.scid = getElement(data, "$.item.scid"); this.searchStr = getElement(data, "$.item.searchStr"); } public DcpMediaContainerMsg(final DcpMediaContainerMsg other) { super(0, CODE); this.browseType = other.browseType; this.sid = other.sid; this.parentSid = other.parentSid; this.cid = other.cid; this.parentCid = other.parentCid; this.mid = other.mid; this.type = other.type; this.container = other.container; this.playable = other.playable; this.name = other.name; this.artist = other.artist; this.album = other.album; this.imageUrl = other.imageUrl; this.start = other.start; this.count = other.count; this.aid = other.aid; this.qid = other.qid; this.layerInfo = other.layerInfo; this.scid = other.scid; this.searchStr = other.searchStr; // Do not copy items } DcpMediaContainerMsg(Map<String, String> tokens, final BrowseType browseType) { super(0, CODE); this.browseType = browseType; this.sid = nonNull(tokens.get("sid")); this.parentSid = this.sid; this.cid = nonNull(tokens.get("cid")); this.parentCid = this.cid; this.container = !cid.isEmpty(); final String[] rangeStr = nonNull(tokens.get("range")).split(","); if (rangeStr.length == 2 && Utils.isInteger(rangeStr[0])) { this.start = Integer.parseInt(rangeStr[0]); } final String countStr = nonNull(tokens.get("count")); if (!countStr.isEmpty() && Utils.isInteger(countStr)) { this.count = Integer.parseInt(countStr); } this.layerInfo = cid.isEmpty() ? ListTitleInfoMsg.LayerInfo.SERVICE_TOP : ListTitleInfoMsg.LayerInfo.UNDER_2ND_LAYER; if (browseType == BrowseType.SEARCH_RESULT) { this.layerInfo = ListTitleInfoMsg.LayerInfo.UNDER_2ND_LAYER; this.scid = nonNull(tokens.get("scid")); this.searchStr = nonNull(tokens.get("search")); } else if (browseType == BrowseType.PLAY_QUEUE) { this.sid = ServiceType.DCP_PLAYQUEUE.getDcpCode().substring(2); } } public DcpMediaContainerMsg(@NonNull Map<String, Object> heosMsg, final String parentSid, final String parentCid) { super(0, CODE); this.browseType = BrowseType.MEDIA_ITEM; this.sid = getElement(heosMsg, "sid"); this.parentSid = parentSid; this.cid = getElement(heosMsg, "cid"); this.parentCid = parentCid; this.mid = getElement(heosMsg, "mid"); this.type = getElement(heosMsg, "type"); this.container = YES.equalsIgnoreCase(getElement(heosMsg, "container")); this.playable = YES.equalsIgnoreCase(getElement(heosMsg, "playable")); this.name = getNameElement(getElement(heosMsg, "name")); this.artist = getNameElement(getElement(heosMsg, "artist")); this.album = getNameElement(getElement(heosMsg, "album")); this.imageUrl = getElement(heosMsg, "image_url"); } public DcpMediaContainerMsg(@NonNull Map<String, Object> heosMsg) { super(0, CODE); browseType = BrowseType.PLAYQUEUE_ITEM; this.sid = ""; this.parentSid = ""; this.cid = ""; this.parentCid = ""; this.mid = getElement(heosMsg, "mid"); this.type = "song"; this.container = false; this.playable = true; this.artist = getElement(heosMsg, "artist"); this.name = this.artist + " - " + getElement(heosMsg, "song"); this.album = getElement(heosMsg, "album"); this.imageUrl = getElement(heosMsg, "image_url"); this.qid = getElement(heosMsg, "qid"); } public boolean keyEqual(@NonNull DcpMediaContainerMsg msg) { return browseType == msg.browseType && sid.equals(msg.sid) && cid.equals(msg.cid); } public BrowseType getBrowseType() { return browseType; } public String getSid() { return sid; } public String getCid() { return cid; } public String getMid() { return mid; } public boolean isContainer() { return container; } public boolean isPlayable() { return playable; } public String getType() { return type; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } public int getCount() { return count; } public void setAid(String aid) { this.aid = aid; } public ListTitleInfoMsg.LayerInfo getLayerInfo() { return layerInfo; } public List<XmlListItemMsg> getItems() { return items; } public boolean isSong() { return "song".equals(type); } public List<XmlListItemMsg> getOptions() { return options; } public String getSearchStr() { return searchStr; } @NonNull @Override public String toString() { return CODE + "[TYPE=" + browseType + ";SID=" + sid + "; PSID=" + parentSid + "; CID=" + cid + "; PCID=" + parentCid + "; MID=" + mid + "; TYPE=" + type + "; CONT=" + container + "; PLAY=" + playable + "; START=" + start + "; COUNT=" + count + (aid.isEmpty() ? EMPTY : "; AID=" + aid) + (qid.isEmpty() ? EMPTY : "; QID=" + qid) + (name.isEmpty() ? EMPTY : "; NAME=" + name) + (artist.isEmpty() ? EMPTY : "; ARTIST=" + artist) + (album.isEmpty() ? EMPTY : "; ALBUM=" + album) + (imageUrl.isEmpty() ? EMPTY : "; IMG=" + imageUrl) + (layerInfo == null ? EMPTY : "; LAYER=" + layerInfo) + (items.isEmpty() ? EMPTY : "; ITEMS=" + items.size()) + (options.isEmpty() ? EMPTY : "; OPTIONS=" + options.size()) + (scid.isEmpty() ? EMPTY : "; SCID=" + scid) + (searchStr.isEmpty() ? EMPTY : "; SEARCH=" + searchStr) + "]"; } @Override public EISCPMessage getCmdMsg() { final StringBuilder sb = new StringBuilder("{\"item\":{"); addJsonParameter(sb, "browseType", String.valueOf(browseType.ordinal()), true); addJsonParameter(sb, "sid", sid, true); addJsonParameter(sb, "parentSid", parentSid, true); addJsonParameter(sb, "cid", cid, true); addJsonParameter(sb, "parentCid", parentCid, true); addJsonParameter(sb, "mid", mid, true); addJsonParameter(sb, "type", type, true); addJsonParameter(sb, "container", container ? "yes" : "no", true); addJsonParameter(sb, "playable", playable ? "yes" : "no", true); addJsonParameter(sb, "name", name, true); addJsonParameter(sb, "start", String.valueOf(start), true); addJsonParameter(sb, "aid", aid, true); addJsonParameter(sb, "qid", qid, true); addJsonParameter(sb, "scid", scid, true); addJsonParameter(sb, "searchStr", searchStr, false); sb.append("}}"); return new EISCPMessage(CODE, sb.toString()); } private void addJsonParameter(@NonNull final StringBuilder sb, @NonNull final String name, @NonNull final String value, boolean intermediate) { sb.append("\"").append(name).append("\": \"").append(value).append("\""); if (intermediate) { sb.append(", "); } } @Nullable public static DcpMediaContainerMsg processHeosMessage(@NonNull final String command, @NonNull final String heosMsg, @NonNull final Map<String, String> tokens) { if (HEOS_RESP_BROWSE_SERV.equals(command) || HEOS_RESP_BROWSE_CONT.equals(command) || HEOS_RESP_BROWSE_SEARCH.equals(command)) { final BrowseType type = HEOS_RESP_BROWSE_SEARCH.equals(command) ? BrowseType.SEARCH_RESULT : BrowseType.MEDIA_LIST; final DcpMediaContainerMsg parentMsg = new DcpMediaContainerMsg(tokens, type); readMediaItems(parentMsg, heosMsg); try { // options are optional readOptions(parentMsg, heosMsg); } catch (Exception ex) { // nothing to do } return parentMsg; } if (HEOS_RESP_BROWSE_QUEUE.equals(command)) { final DcpMediaContainerMsg parentMsg = new DcpMediaContainerMsg(tokens, BrowseType.PLAY_QUEUE); readPlayQueueItems(parentMsg, heosMsg); return parentMsg; } return null; } private static void readMediaItems(DcpMediaContainerMsg parentMsg, String heosMsg) { final JSONArray payload = JsonPath.parse(heosMsg).read("$.payload"); for (int i = 0; i < payload.size(); i++) { @SuppressWarnings("unchecked") final DcpMediaContainerMsg itemMsg = new DcpMediaContainerMsg( (LinkedHashMap<String, Object>) payload.get(i), parentMsg.sid, parentMsg.cid); if (itemMsg.isSong()) { itemMsg.setAid("1"); } final XmlListItemMsg xmlItem = new XmlListItemMsg( i + parentMsg.start, parentMsg.layerInfo == ListTitleInfoMsg.LayerInfo.SERVICE_TOP ? 0 : 1, itemMsg.name, XmlListItemMsg.Icon.UNKNOWN, true, itemMsg); if (itemMsg.container) { xmlItem.setIconType(itemMsg.name.equals("All") ? "01" : itemMsg.name.equals("Browse Folders") ? "99" : "50"); xmlItem.setIcon(itemMsg.playable ? XmlListItemMsg.Icon.FOLDER_PLAY : XmlListItemMsg.Icon.FOLDER); } else { xmlItem.setIconType("75"); xmlItem.setIcon(itemMsg.playable ? XmlListItemMsg.Icon.MUSIC : XmlListItemMsg.Icon.UNKNOWN); } parentMsg.items.add(xmlItem); } } private static void readPlayQueueItems(DcpMediaContainerMsg parentMsg, String heosMsg) { final JSONArray payload = JsonPath.parse(heosMsg).read("$.payload"); for (int i = 0; i < payload.size(); i++) { @SuppressWarnings("unchecked") final DcpMediaContainerMsg itemMsg = new DcpMediaContainerMsg( (LinkedHashMap<String, Object>) payload.get(i)); final XmlListItemMsg xmlItem = new XmlListItemMsg( Integer.parseInt(itemMsg.qid), 0, itemMsg.name, XmlListItemMsg.Icon.MUSIC, true, itemMsg); xmlItem.setIconType("75"); parentMsg.items.add(xmlItem); } } private static void readOptions(final DcpMediaContainerMsg parentMsg, String heosMsg) { final List<Map<String, JSONArray>> options = JsonPath.parse(heosMsg).read("$.options[*]"); final JSONArray browse = options.isEmpty() ? null : options.get(0).get("browse"); if (browse == null) { return; } for (int i = 0; i < browse.size(); i++) { @SuppressWarnings("unchecked") final LinkedHashMap<String, Object> item = (LinkedHashMap<String, Object>) browse.get(i); final int id = Integer.parseInt(getElement(item, "id")); final String name = getElement(item, "name"); if (id == SO_CONTAINER) { parentMsg.options.add(new XmlListItemMsg(SO_ADD_ALL, 0, name, XmlListItemMsg.Icon.FOLDER_PLAY, true, null)); parentMsg.options.add(new XmlListItemMsg(SO_ADD_AND_PLAY_ALL, 0, name, XmlListItemMsg.Icon.FOLDER_PLAY, true, null)); parentMsg.options.add(new XmlListItemMsg(SO_REPLACE_AND_PLAY_ALL, 0, name, XmlListItemMsg.Icon.FOLDER_PLAY, true, null)); } else { parentMsg.options.add(new XmlListItemMsg(id, 0, name, XmlListItemMsg.Icon.UNKNOWN, true, null)); } } } @SuppressLint("DefaultLocale") @Nullable @Override public String buildDcpMsg(boolean isQuery) { if (aid.startsWith(HEOS_SET_SERVICE_OPTION)) { switch (start) { case SO_ADD_TO_HEOS: // Add station to HEOS Favorites return String.format("heos://browse/set_service_option?sid=%s&option=19&mid=%s&name=%s", parentSid, mid, name); case SO_REMOVE_FROM_HEOS: // Remove from HEOS Favorites return String.format("heos://browse/set_service_option?option=20&mid=%s", mid); case SO_ADD_AND_PLAY_ALL: // Add and play return String.format("heos://browse/add_to_queue?pid=%s&sid=%s&cid=%s&aid=1", DCP_HEOS_PID, parentSid, parentCid); case SO_ADD_ALL: // Add return String.format("heos://browse/add_to_queue?pid=%s&sid=%s&cid=%s&aid=3", DCP_HEOS_PID, parentSid, parentCid); case SO_REPLACE_AND_PLAY_ALL: // Replace and play return String.format("heos://browse/add_to_queue?pid=%s&sid=%s&cid=%s&aid=4", DCP_HEOS_PID, parentSid, parentCid); } } else if (container) { if (playable && !parentSid.isEmpty() && !cid.isEmpty() && !aid.isEmpty()) { return String.format("heos://browse/add_to_queue?pid=%s&sid=%s&cid=%s&aid=%s", DCP_HEOS_PID, parentSid, cid, aid); } if (!parentSid.isEmpty() && !cid.isEmpty()) { return String.format("heos://browse/browse?sid=%s&cid=%s&range=%d,9999", parentSid, cid, start); } } else { if (!playable) { if (browseType == BrowseType.PLAY_QUEUE) { return String.format("heos://player/get_queue?pid=%s&range=%d,9999", DCP_HEOS_PID, start); } else if (browseType == BrowseType.SEARCH_RESULT) { return String.format("heos://browse/search?sid=%s&search=%s&scid=%s&range=%d,9999", sid, searchStr, scid, start); } else if (!sid.isEmpty()) { return String.format("heos://browse/browse?sid=%s", sid); } } if (playable && !mid.isEmpty()) { if ("station".equals(type) && !parentSid.isEmpty()) { if (!parentCid.isEmpty()) { return String.format("heos://browse/play_stream?pid=%s&sid=%s&cid=%s&mid=%s", DCP_HEOS_PID, parentSid, parentCid, mid); } else { return String.format("heos://browse/play_stream?pid=%s&sid=%s&mid=%s", DCP_HEOS_PID, parentSid, mid); } } if (isSong() && !parentSid.isEmpty()) { if (!parentCid.isEmpty()) { return String.format("heos://browse/add_to_queue?pid=%s&sid=%s&cid=%s&mid=%s&aid=%s", DCP_HEOS_PID, parentSid, parentCid, mid, aid); } else { return String.format("heos://browse/add_to_queue?pid=%s&sid=%s&mid=%s&aid=%s", DCP_HEOS_PID, parentSid, mid, aid); } } } if (playable && browseType == BrowseType.PLAYQUEUE_ITEM && !qid.isEmpty()) { return String.format("heos://player/play_queue?pid=%s&qid=%s", DCP_HEOS_PID, qid); } } return null; } @NonNull private static String nonNull(@Nullable final String inp) { return inp == null ? EMPTY : inp; } @NonNull private static String getElement(Map<String, Object> payload, String name) { final Object obj = payload.get(name); if (obj != null) { if (obj instanceof Integer) { return Integer.toString((Integer) obj); } if (obj instanceof String) { return (String) obj; } Logging.info(payload, "DCP HEOS error: Cannot read element " + name + ": object type unknown: " + obj); } return EMPTY; } @NonNull private static String getElement(@NonNull final String heosMsg, @NonNull final String path) { try { final Object obj = JsonPath.read(heosMsg, path); if (obj instanceof Integer) { return Integer.toString((Integer) obj); } if (obj instanceof String) { return (String) obj; } Logging.info(heosMsg, "DCP HEOS error: Cannot read path " + path + ": object type unknown: " + obj); return EMPTY; } catch (Exception ex) { return EMPTY; } } @NonNull private static String getNameElement(@NonNull final String name) { return name.replace("%26", "&") .replace("%3D", "=") .replace("%25", "%"); } }
22,597
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
PrivacyPolicyStatusMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/PrivacyPolicyStatusMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /* * Privacy Policy Status message */ public class PrivacyPolicyStatusMsg extends ISCPMessage { public final static String CODE = "PPS"; public enum Status implements StringParameterIf { NONE("000", -1), ONKYO("100", R.string.privacy_policy_onkyo), GOOGLE("010", R.string.privacy_policy_google), SUE("001", R.string.privacy_policy_sue); final String code; @StringRes final int descriptionId; Status(final String code, @StringRes final int descriptionId) { this.code = code; this.descriptionId = descriptionId; } public String getCode() { return code; } @SuppressWarnings("unused") @StringRes public int getDescriptionId() { return descriptionId; } } private final Status status; PrivacyPolicyStatusMsg(EISCPMessage raw) throws Exception { super(raw); status = (Status) searchParameter(data, Status.values(), Status.NONE); } @NonNull @Override public String toString() { return CODE + "[" + getData() + "]"; } @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean isPolicySet(Status s) { if (getData() == null || getData().length() < 3) { return false; } switch (s) { case NONE: return getData().equals(Status.NONE.getCode()); case ONKYO: return getData().charAt(0) == '1'; case GOOGLE: return getData().charAt(1) == '1'; case SUE: return getData().charAt(2) == '1'; } return false; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, status.getCode()); } @Override public boolean hasImpactOnMediaList() { return false; } }
2,855
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
FirmwareUpdateMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/FirmwareUpdateMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.jayway.jsonpath.JsonPath; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; /* * Firmware Update message */ public class FirmwareUpdateMsg extends ISCPMessage { public final static String CODE = "UPD"; public enum Status implements DcpStringParameterIf { NONE("N/A", "N/A", R.string.device_firmware_none), ACTUAL("FF", "update_none", R.string.device_firmware_actual), NEW_VERSION("00", "update_exist", R.string.device_firmware_new_version), NEW_VERSION_NORMAL("01", "N/A", R.string.device_firmware_new_version), NEW_VERSION_FORCE("02", "N/A", R.string.device_firmware_new_version), UPDATE_STARTED("Dxx-xx", "N/A", R.string.device_firmware_update_started), UPDATE_COMPLETE("CMP", "N/A", R.string.device_firmware_update_complete), NET("NET", "N/A", R.string.device_firmware_net); final String code, dcpCode; @StringRes final int descriptionId; Status(final String code, final String dcpCode, @StringRes final int descriptionId) { this.code = code; this.dcpCode = dcpCode; this.descriptionId = descriptionId; } public String getCode() { return code; } @NonNull public String getDcpCode() { return dcpCode; } @StringRes public int getDescriptionId() { return descriptionId; } } private final Status status; FirmwareUpdateMsg(EISCPMessage raw) throws Exception { super(raw); status = (Status) searchParameter(data, Status.values(), Status.NONE); } public FirmwareUpdateMsg(Status status) { super(0, null); this.status = status; } public Status getStatus() { return status; } @NonNull @Override public String toString() { return CODE + "[" + data + "; STATUS=" + status.getCode() + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, status.getCode()); } @Override public boolean hasImpactOnMediaList() { return false; } /* * Denon control protocol */ private final static String HEOS_COMMAND = "player/check_update"; @Nullable public static FirmwareUpdateMsg processHeosMessage(@NonNull final String command, @NonNull final String heosMsg) { if (HEOS_COMMAND.equals(command)) { final Status s = (Status) searchDcpParameter( JsonPath.read(heosMsg, "$.payload.update"), Status.values(), null); if (s != null) { return new FirmwareUpdateMsg(s); } } return null; } @Nullable @Override public String buildDcpMsg(boolean isQuery) { if (isQuery) { return "heos://" + HEOS_COMMAND + "?pid=" + DCP_HEOS_PID; } return null; } }
3,919
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
VideoInformationMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/VideoInformationMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; /* * Video Information Command message */ public class VideoInformationMsg extends ISCPMessage { public final static String CODE = "IFV"; /* * Information of Video(Same Immediate Display ',' is separator of informations) * a…a: Video Input Port * b…b: Input Resolution, Frame Rate * c…c: RGB/YCbCr * d…d: Color Depth * e…e: Video Output Port * f…f: Output Resolution, Frame Rate * g…g: RGB/YCbCr * h…h: Color Depth * i...i: Picture Mode */ public final String videoInput; public final String videoOutput; VideoInformationMsg(EISCPMessage raw) throws Exception { super(raw); final String[] pars = data.split(COMMA_SEP); videoInput = getTags(pars, 0, 4); videoOutput = getTags(pars, 4, pars.length); } @NonNull @Override public String toString() { return CODE + "[" + getData() + "; IN=" + videoInput + "; OUT=" + videoOutput + "]"; } }
1,836
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
GoogleCastAnalyticsMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/GoogleCastAnalyticsMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /* * Google Cast Share Usage Data Command */ public class GoogleCastAnalyticsMsg extends ISCPMessage { public final static String CODE = "NGU"; public enum Status implements StringParameterIf { NONE("N/A", R.string.device_two_way_switch_none), OFF("00", R.string.device_two_way_switch_off), ON("01", R.string.device_two_way_switch_on); final String code; @StringRes final int descriptionId; Status(final String code, @StringRes final int descriptionId) { this.code = code; this.descriptionId = descriptionId; } public String getCode() { return code; } @StringRes public int getDescriptionId() { return descriptionId; } } private final Status status; GoogleCastAnalyticsMsg(EISCPMessage raw) throws Exception { super(raw); status = (Status) searchParameter(data, Status.values(), Status.NONE); } public GoogleCastAnalyticsMsg(Status level) { super(0, null); this.status = level; } public Status getStatus() { return status; } @NonNull @Override public String toString() { return CODE + "[" + status.toString() + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, status.getCode()); } @Override public boolean hasImpactOnMediaList() { return false; } public static Status toggle(Status s) { return (s == Status.OFF) ? Status.ON : Status.OFF; } }
2,560
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
PresetMemoryMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/PresetMemoryMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import android.annotation.SuppressLint; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import java.util.ArrayList; import java.util.Collections; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /* * Preset Memory Command (Include Tuner Pack Model Only) * sets Preset No. 1 - 40 (In hexadecimal representation) */ public class PresetMemoryMsg extends ISCPMessage { public final static String CODE = "PRM"; public final static int MAX_NUMBER = 40; private int preset; PresetMemoryMsg(EISCPMessage raw) throws Exception { super(raw); try { preset = Integer.parseInt(data, 16); } catch (Exception e) { // nothing to do } } public PresetMemoryMsg(final int preset) { super(0, null); this.preset = preset; } @NonNull @Override public String toString() { return CODE + "[" + preset + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, String.format("%02x", preset)); } @Override public boolean hasImpactOnMediaList() { return false; } /* * Denon control protocol */ private final static String DCP_COMMAND_STATUS = "OPTPSTUNER"; @NonNull public static ArrayList<String> getAcceptedDcpCodes() { return new ArrayList<>(Collections.singletonList(DCP_COMMAND_STATUS)); } @Nullable public static PresetMemoryMsg processDcpMessage(@NonNull String dcpMsg) { if (dcpMsg.startsWith(DCP_COMMAND_STATUS)) { final String par = dcpMsg.substring(DCP_COMMAND_STATUS.length()).trim(); final String[] pars = par.split(" "); if (pars.length > 1) { return new PresetMemoryMsg(Integer.parseInt(pars[0])); } } return null; } @SuppressLint("DefaultLocale") @Nullable @Override public String buildDcpMsg(boolean isQuery) { // For some reason, TPANMEM does not work for DAB stations: // return "TPANMEM" + (isQuery ? DCP_MSG_REQ : String.format("%02d", preset)); // Use APP_COMMAND instead: return String.format("<cmd id=\"1\">SetTunerPresetMemory</cmd><presetno>%d</presetno>", preset); } }
3,114
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
CdPlayerOperationCommandMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/CdPlayerOperationCommandMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /* * CD Player Operation Command */ public class CdPlayerOperationCommandMsg extends ISCPMessage { public final static String CODE = "CCD"; // Controls that allow the control of build-in CD player via CCD command public final static String CONTROL_CD_INT1 = "CD Control"; public final static String CONTROL_CD_INT2 = "CD Control(NewRemote)"; public enum Command implements StringParameterIf { POWER(R.string.cd_cmd_power, R.drawable.menu_power_standby), TRACK(R.string.cd_cmd_track), PLAY(R.string.cd_cmd_play, R.drawable.cmd_play), STOP(R.string.cd_cmd_stop, R.drawable.cmd_stop), PAUSE(R.string.cd_cmd_pause, R.drawable.cmd_pause), SKIP_F(R.string.cd_cmd_skip_f, R.drawable.cmd_next, "SKIP.F"), SKIP_R(R.string.cd_cmd_skip_r, R.drawable.cmd_previous, "SKIP.R"), MEMORY(R.string.cd_cmd_memory), CLEAR(R.string.cd_cmd_clear), REPEAT(R.string.cd_cmd_repeat, R.drawable.repeat_all), RANDOM(R.string.cd_cmd_random, R.drawable.cmd_random), DISP(R.string.cd_cmd_disp), D_MODE(R.string.cd_cmd_d_mode), FF(R.string.cd_cmd_ff), REW(R.string.cd_cmd_rew), OP_CL(R.string.cd_cmd_op_cl, R.drawable.cd_eject, "OP/CL"), NUMBER_1(R.string.cd_cmd_number_1, "1"), NUMBER_2(R.string.cd_cmd_number_2, "2"), NUMBER_3(R.string.cd_cmd_number_3, "3"), NUMBER_4(R.string.cd_cmd_number_4, "4"), NUMBER_5(R.string.cd_cmd_number_5, "5"), NUMBER_6(R.string.cd_cmd_number_6, "6"), NUMBER_7(R.string.cd_cmd_number_7, "7"), NUMBER_8(R.string.cd_cmd_number_8, "8"), NUMBER_9(R.string.cd_cmd_number_9, "9"), NUMBER_0(R.string.cd_cmd_number_0, "0"), NUMBER_10(R.string.cd_cmd_number_10, "10"), NUMBER_GREATER_10(R.string.cd_cmd_number_greater_10, "+10"), DISC_F(R.string.cd_cmd_disc_f), DISC_R(R.string.cd_cmd_disc_r), DISC1(R.string.cd_cmd_disc1), DISC2(R.string.cd_cmd_disc2), DISC3(R.string.cd_cmd_disc3), DISC4(R.string.cd_cmd_disc4), DISC5(R.string.cd_cmd_disc5), DISC6(R.string.cd_cmd_disc6); @StringRes final int descriptionId; @DrawableRes final int imageId; final String cmd; Command(@StringRes final int descriptionId) { this.descriptionId = descriptionId; this.imageId = R.drawable.media_item_unknown; this.cmd = null; } Command(@StringRes final int descriptionId, @DrawableRes final int imageId) { this.descriptionId = descriptionId; this.imageId = imageId; this.cmd = null; } Command(@StringRes final int descriptionId, final String cmd) { this.descriptionId = descriptionId; this.imageId = R.drawable.media_item_unknown; this.cmd = cmd; } Command(@StringRes final int descriptionId, @DrawableRes final int imageId, final String cmd) { this.descriptionId = descriptionId; this.imageId = imageId; this.cmd = cmd; } public String getCode() { return toString(); } @StringRes public int getDescriptionId() { return descriptionId; } @DrawableRes public int getImageId() { return imageId; } String getCmd() { return cmd != null ? cmd : getCode(); } } private final Command command; CdPlayerOperationCommandMsg(EISCPMessage raw) throws Exception { super(raw); this.command = (Command) searchParameter(data, Command.values(), null); } public CdPlayerOperationCommandMsg(final String command) { super(0, null); this.command = (Command) searchParameter(command, Command.values(), null); } public Command getCommand() { return command; } @NonNull @Override public String toString() { return CODE + "[" + data + "; CMD=" + (command == null ? "null" : command.getCmd()) + "]"; } @Override public EISCPMessage getCmdMsg() { return command == null ? null : new EISCPMessage(CODE, command.getCmd()); } @Override public boolean hasImpactOnMediaList() { return false; } @NonNull public static String convertOpCommand(@NonNull final String opCommand) { switch (opCommand) { case "TRDN": return Command.SKIP_R.getCode(); case "TRUP": return Command.SKIP_F.getCode(); default: return opCommand; } } }
5,767
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
DcpSearchMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/DcpSearchMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /* * Denon control protocol - Search * Command: heos://browse/search?sid=source_id&search=search_string&scid=search_criteria&range=start#, end# */ public class DcpSearchMsg extends ISCPMessage { public final static String CODE = "D09"; private final static String HEOS_COMMAND = "browse/search"; private final String sid; private final String scid; private final String searchStr; DcpSearchMsg(EISCPMessage raw) throws Exception { super(raw); final String[] tags = data.split(ISCPMessage.DCP_MSG_SEP); sid = tags.length > 0 ? tags[0] : ""; scid = tags.length > 1 ? tags[1] : ""; searchStr = tags.length >= 2 ? tags[2] : ""; } public DcpSearchMsg(String sid, String scid, String searchStr) { super(0, null); this.sid = sid; this.scid = scid; this.searchStr = searchStr; } @NonNull @Override public String toString() { return CODE + "[SID=" + sid + ", SCID=" + scid + ", STR=" + searchStr + "]"; } @Override public EISCPMessage getCmdMsg() { final String param = sid + ISCPMessage.DCP_MSG_SEP + scid + ISCPMessage.DCP_MSG_SEP + searchStr; return new EISCPMessage(CODE, param); } @Override public boolean hasImpactOnMediaList() { return false; } @Nullable @Override public String buildDcpMsg(boolean isQuery) { return !sid.isEmpty() && !scid.isEmpty() ? String.format("heos://%s?sid=%s&search=%s&scid=%s", HEOS_COMMAND, sid, searchStr, scid) : null; } }
2,478
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
PresetCommandMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/PresetCommandMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import android.annotation.SuppressLint; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ZonedMessage; import com.mkulesh.onpc.utils.Logging; import java.util.ArrayList; import java.util.Collections; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; /* * Preset Command (Include Tuner Pack Model Only) */ public class PresetCommandMsg extends ZonedMessage { public final static String CODE = "PRS"; final static String ZONE2_CODE = "PRZ"; final static String ZONE3_CODE = "PR3"; final static String ZONE4_CODE = "PR4"; public final static String[] ZONE_COMMANDS = new String[]{ CODE, ZONE2_CODE, ZONE3_CODE, ZONE4_CODE }; public final static int NO_PRESET = -1; public enum Command implements DcpStringParameterIf { UP(R.string.preset_command_up, R.drawable.cmd_right), DOWN(R.string.preset_command_down, R.drawable.cmd_left); @StringRes final int descriptionId; @DrawableRes final int imageId; Command(@StringRes final int descriptionId, @DrawableRes final int imageId) { this.descriptionId = descriptionId; this.imageId = imageId; } public String getCode() { return toString(); } @NonNull public String getDcpCode() { return toString(); } @StringRes public int getDescriptionId() { return descriptionId; } @DrawableRes public int getImageId() { return imageId; } } private final Command command; private final ReceiverInformationMsg.Preset presetConfig; private int preset = NO_PRESET; PresetCommandMsg(EISCPMessage raw) throws Exception { super(raw, ZONE_COMMANDS); command = (Command) searchParameter(data, Command.values(), null); presetConfig = null; try { preset = command == null ? Integer.parseInt(data, 16) : NO_PRESET; } catch (Exception e) { // nothing to do } } public PresetCommandMsg(int zoneIndex, final String command) { super(0, null, zoneIndex); this.command = (Command) searchParameter(command, Command.values(), null); this.presetConfig = null; this.preset = NO_PRESET; } public PresetCommandMsg(int zoneIndex, final ReceiverInformationMsg.Preset presetConfig, final int preset) { super(0, null, zoneIndex); this.command = null; this.presetConfig = presetConfig; this.preset = preset; } @Override public String getZoneCommand() { return ZONE_COMMANDS[zoneIndex]; } public Command getCommand() { return command; } public ReceiverInformationMsg.Preset getPresetConfig() { return presetConfig; } public int getPreset() { return preset; } @NonNull @Override public String toString() { return getZoneCommand() + "[" + data + "; ZONE_INDEX=" + zoneIndex + "; CMD=" + (command != null ? command.toString() : "null") + "; PRS_CFG=" + (presetConfig != null ? presetConfig.getName() : "null") + "; PRESET=" + preset + "]"; } @Override public EISCPMessage getCmdMsg() { String par = ""; if (command != null) { par = command.getCode(); } else if (presetConfig != null) { par = String.format("%02x", presetConfig.getId()); } return new EISCPMessage(getZoneCommand(), par); } @Override public boolean hasImpactOnMediaList() { return false; } /* * Denon control protocol. The same message is used for both zones. */ private final static String DCP_COMMAND = "TPAN"; private final static String DCP_COMMAND_OFF = "OFF"; @NonNull public static ArrayList<String> getAcceptedDcpCodes() { return new ArrayList<>(Collections.singletonList(DCP_COMMAND)); } public static PresetCommandMsg processDcpMessage(@NonNull String dcpMsg, int zone) { if (dcpMsg.startsWith(DCP_COMMAND)) { final String par = dcpMsg.substring(DCP_COMMAND.length()).trim(); if (par.equalsIgnoreCase(DCP_COMMAND_OFF)) { return new PresetCommandMsg(zone, null, NO_PRESET); } try { final int preset = Integer.parseInt(par); return new PresetCommandMsg(zone, null, preset); } catch (Exception e) { Logging.info(PresetCommandMsg.class, "Unable to parse preset " + par); return null; } } return null; } @SuppressLint("DefaultLocale") @Nullable @Override public String buildDcpMsg(boolean isQuery) { return DCP_COMMAND + (isQuery ? DCP_MSG_REQ : (command != null ? command.getDcpCode() : String.format("%02d", preset))); } }
6,036
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
TuningCommandMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/TuningCommandMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ZonedMessage; import com.mkulesh.onpc.utils.Utils; import java.util.ArrayList; import java.util.Arrays; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; /* * Tuning Command (Include Tuner Pack Model Only) */ public class TuningCommandMsg extends ZonedMessage { public final static String CODE = "TUN"; final static String ZONE2_CODE = "TUZ"; final static String ZONE3_CODE = "TU3"; final static String ZONE4_CODE = "TU4"; public final static String[] ZONE_COMMANDS = new String[]{ CODE, ZONE2_CODE, ZONE3_CODE, ZONE4_CODE }; public enum Command implements DcpStringParameterIf { UP(R.string.tuning_command_up, R.drawable.cmd_fast_forward), DOWN(R.string.tuning_command_down, R.drawable.cmd_fast_backward); @StringRes final int descriptionId; @DrawableRes final int imageId; Command(@StringRes final int descriptionId, @DrawableRes final int imageId) { this.descriptionId = descriptionId; this.imageId = imageId; } public String getCode() { return toString(); } @NonNull public String getDcpCode() { return toString(); } @StringRes public int getDescriptionId() { return descriptionId; } @DrawableRes public int getImageId() { return imageId; } } private final Command command; private final String frequency; private final DcpTunerModeMsg.TunerMode dcpTunerMode; TuningCommandMsg(EISCPMessage raw) throws Exception { super(raw, ZONE_COMMANDS); this.command = (Command) searchParameter(data, Command.values(), null); this.frequency = (command == null) ? data : ""; this.dcpTunerMode = DcpTunerModeMsg.TunerMode.NONE; } public TuningCommandMsg(int zoneIndex, final String command) { super(0, null, zoneIndex); this.command = (Command) searchParameter(command, Command.values(), null); this.frequency = ""; this.dcpTunerMode = DcpTunerModeMsg.TunerMode.NONE; } public TuningCommandMsg(int zone, String frequency, @NonNull DcpTunerModeMsg.TunerMode dcpTunerMode) { super(0, null, zone); this.command = null; this.frequency = String.valueOf(frequency); this.dcpTunerMode = dcpTunerMode; } @Override public String getZoneCommand() { return ZONE_COMMANDS[zoneIndex]; } public Command getCommand() { return command; } public String getFrequency() { return frequency; } @NonNull @Override public String toString() { return getZoneCommand() + "[" + data + "; ZONE_INDEX=" + zoneIndex + "; CMD=" + (command != null ? command.toString() : "null") + "; FREQ=" + frequency + "; MODE=" + dcpTunerMode + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(getZoneCommand(), command.getCode()); } @Override public boolean hasImpactOnMediaList() { return false; } /* * Denon control protocol */ private final static String DCP_COMMAND_FM = "TFAN"; private final static String DCP_COMMAND_DAB = "DAFRQ"; @NonNull public static ArrayList<String> getAcceptedDcpCodes() { return new ArrayList<>(Arrays.asList(DCP_COMMAND_FM, DCP_COMMAND_DAB)); } @Nullable public static TuningCommandMsg processDcpMessage(@NonNull String dcpMsg, int zone) { if (dcpMsg.startsWith(DCP_COMMAND_FM)) { final String par = dcpMsg.substring(DCP_COMMAND_FM.length()).trim(); if (Utils.isInteger(par)) { return new TuningCommandMsg(zone, par, DcpTunerModeMsg.TunerMode.FM); } } if (dcpMsg.startsWith(DCP_COMMAND_DAB)) { final String par = dcpMsg.substring(DCP_COMMAND_DAB.length()).trim(); return new TuningCommandMsg(zone, par, DcpTunerModeMsg.TunerMode.DAB); } return null; } @Nullable @Override public String buildDcpMsg(boolean isQuery) { if (zoneIndex == ReceiverInformationMsg.DEFAULT_ACTIVE_ZONE) { // Only available for main zone return DCP_COMMAND_FM + (isQuery ? DCP_MSG_REQ : (command != null ? command.getDcpCode() : null)); } return null; } @NonNull public DcpTunerModeMsg.TunerMode getDcpTunerMode() { return dcpTunerMode; } }
5,627
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
CenterLevelCommandMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/CenterLevelCommandMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import com.mkulesh.onpc.utils.Utils; import androidx.annotation.NonNull; /* * Center (temporary) Level Command */ public class CenterLevelCommandMsg extends ISCPMessage { public final static String CODE = "CTL"; public final static String KEY = "Center Level"; public final static int NO_LEVEL = 0xFF; private int level, cmdLength; CenterLevelCommandMsg(EISCPMessage raw) throws Exception { super(raw); try { level = Integer.parseInt(data, 16); cmdLength = getData().length(); } catch (Exception e) { level = NO_LEVEL; cmdLength = NO_LEVEL; } } public CenterLevelCommandMsg(int level, int cmdLength) { super(0, null); this.level = level; this.cmdLength = cmdLength; } public int getLevel() { return level; } public int getCmdLength() { return cmdLength; } @NonNull @Override public String toString() { return CODE + "[" + data + "; LEVEL=" + level + "; CMD_LENGTH=" + cmdLength + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, Utils.intLevelToString(level, cmdLength)); } @Override public boolean hasImpactOnMediaList() { return false; } }
2,169
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
GoogleCastVersionMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/GoogleCastVersionMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; /* * Google Cast Version Command */ public class GoogleCastVersionMsg extends ISCPMessage { public final static String CODE = "NGV"; GoogleCastVersionMsg(EISCPMessage raw) throws Exception { super(raw); } @NonNull @Override public String toString() { return CODE + "[" + data + "]"; } }
1,180
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
ListeningModeMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/ListeningModeMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import java.util.ArrayList; import java.util.Collections; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; /* * Listening Mode Command */ public class ListeningModeMsg extends ISCPMessage { public final static String CODE = "LMD"; public enum Mode implements DcpStringParameterIf { // Integra MODE_00("00", R.string.listening_mode_mode_00), MODE_01("01", R.string.listening_mode_mode_01, true), MODE_02("02", R.string.listening_mode_mode_02), MODE_03("03", R.string.listening_mode_mode_03), MODE_04("04", R.string.listening_mode_mode_04), MODE_05("05", R.string.listening_mode_mode_05), MODE_06("06", R.string.listening_mode_mode_06), MODE_07("07", R.string.listening_mode_mode_07), MODE_08("08", R.string.listening_mode_mode_08), MODE_09("09", R.string.listening_mode_mode_09), MODE_0A("0A", R.string.listening_mode_mode_0a), MODE_0B("0B", R.string.listening_mode_mode_0b), MODE_0C("0C", R.string.listening_mode_mode_0c), MODE_0D("0D", R.string.listening_mode_mode_0d), MODE_0E("0E", R.string.listening_mode_mode_0e), MODE_0F("0F", R.string.listening_mode_mode_0f), MODE_11("11", R.string.listening_mode_mode_11, true), MODE_12("12", R.string.listening_mode_mode_12), MODE_13("13", R.string.listening_mode_mode_13), MODE_14("14", R.string.listening_mode_mode_14), MODE_15("15", R.string.listening_mode_mode_15), MODE_16("16", R.string.listening_mode_mode_16), MODE_17("17", R.string.listening_mode_mode_17), MODE_1F("1F", R.string.listening_mode_mode_1f), MODE_40("40", R.string.listening_mode_mode_40), MODE_41("41", R.string.listening_mode_mode_41), MODE_42("42", R.string.listening_mode_mode_42), MODE_43("43", R.string.listening_mode_mode_43), MODE_44("44", R.string.listening_mode_mode_44), MODE_45("45", R.string.listening_mode_mode_45), MODE_50("50", R.string.listening_mode_mode_50), MODE_51("51", R.string.listening_mode_mode_51), MODE_52("52", R.string.listening_mode_mode_52), MODE_80("80", R.string.listening_mode_mode_80), MODE_81("81", R.string.listening_mode_mode_81), MODE_82("82", R.string.listening_mode_mode_82), MODE_83("83", R.string.listening_mode_mode_83), MODE_84("84", R.string.listening_mode_mode_84), MODE_85("85", R.string.listening_mode_mode_85), MODE_86("86", R.string.listening_mode_mode_86), MODE_87("87", R.string.listening_mode_mode_87), MODE_88("88", R.string.listening_mode_mode_88), MODE_89("89", R.string.listening_mode_mode_89), MODE_8A("8A", R.string.listening_mode_mode_8a), MODE_8B("8B", R.string.listening_mode_mode_8b), MODE_8C("8C", R.string.listening_mode_mode_8c), MODE_8D("8D", R.string.listening_mode_mode_8d), MODE_8E("8E", R.string.listening_mode_mode_8e), MODE_8F("8F", R.string.listening_mode_mode_8f), MODE_90("90", R.string.listening_mode_mode_90), MODE_91("91", R.string.listening_mode_mode_91), MODE_92("92", R.string.listening_mode_mode_92), MODE_93("93", R.string.listening_mode_mode_93), MODE_94("94", R.string.listening_mode_mode_94), MODE_95("95", R.string.listening_mode_mode_95), MODE_96("96", R.string.listening_mode_mode_96), MODE_97("97", R.string.listening_mode_mode_97), MODE_98("98", R.string.listening_mode_mode_98), MODE_99("99", R.string.listening_mode_mode_99), MODE_9A("9A", R.string.listening_mode_mode_9a), MODE_A0("A0", R.string.listening_mode_mode_a0), MODE_A1("A1", R.string.listening_mode_mode_a1), MODE_A2("A2", R.string.listening_mode_mode_a2), MODE_A3("A3", R.string.listening_mode_mode_a3), MODE_A4("A4", R.string.listening_mode_mode_a4), MODE_A5("A5", R.string.listening_mode_mode_a5), MODE_A6("A6", R.string.listening_mode_mode_a6), MODE_A7("A7", R.string.listening_mode_mode_a7), MODE_FF("FF", R.string.listening_mode_mode_ff), // Denon DCP_DIRECT("DIRECT", R.string.listening_mode_mode_01, true), DCP_PURE_DIRECT("PURE DIRECT", R.string.listening_mode_pure_direct, true), DCP_STEREO("STEREO", R.string.listening_mode_mode_00), DCP_AUTO("AUTO", R.string.listening_mode_auto), DCP_DOLBY_DIGITAL("DOLBY DIGITAL", R.string.listening_mode_mode_40), DCP_DTS_SURROUND("DTS SURROUND", R.string.listening_mode_dts_surround), DCP_AURO3D("AURO3D", R.string.listening_mode_auro3d), DCP_AURO2DSURR("AURO2DSURR", R.string.listening_mode_auro2d_surr), DCP_MCH_STEREO("MCH STEREO", R.string.listening_mode_mch_stereo), DCP_WIDE_SCREEN("WIDE SCREEN", R.string.listening_mode_wide_screen), DCP_SUPER_STADIUM("SUPER STADIUM", R.string.listening_mode_super_stadium), DCP_ROCK_ARENA("ROCK ARENA", R.string.listening_mode_rock_arena), DCP_JAZZ_CLUB("JAZZ CLUB", R.string.listening_mode_jazz_club), DCP_CLASSIC_CONCERT("CLASSIC CONCERT", R.string.listening_mode_classic_concert), DCP_MONO_MOVIE("MONO MOVIE", R.string.listening_mode_mono_movie), DCP_MATRIX("MATRIX", R.string.listening_mode_matrix), DCP_VIDEO_GAME("VIDEO GAME", R.string.listening_mode_video_game), DCP_VIRTUAL("VIRTUAL", R.string.listening_mode_vitrual), UP("UP", R.string.listening_mode_up, R.drawable.cmd_right), DOWN("DOWN", R.string.listening_mode_down, R.drawable.cmd_left); final String code; @StringRes final int descriptionId; // For direct mode, the tone control is disabled final boolean directMode; @DrawableRes final int imageId; Mode(final String code, @StringRes final int descriptionId) { this.code = code; this.descriptionId = descriptionId; this.directMode = false; this.imageId = -1; } @SuppressWarnings("SameParameterValue") Mode(final String code, @StringRes final int descriptionId, final boolean directMode) { this.code = code; this.descriptionId = descriptionId; this.directMode = directMode; this.imageId = -1; } Mode(final String code, @StringRes final int descriptionId, @DrawableRes final int imageId) { this.code = code; this.descriptionId = descriptionId; this.directMode = false; this.imageId = imageId; } public String getCode() { return code; } @NonNull public String getDcpCode() { return code; } @StringRes public int getDescriptionId() { return descriptionId; } public boolean isDirectMode() { return directMode; } @DrawableRes public int getImageId() { return imageId; } } private final Mode mode; ListeningModeMsg(EISCPMessage raw) throws Exception { super(raw); mode = (Mode) searchParameter(data, Mode.values(), Mode.MODE_FF); } public ListeningModeMsg(Mode mode) { super(0, null); this.mode = mode; } public Mode getMode() { return mode; } @NonNull @Override public String toString() { return CODE + "[" + data + "; MODE=" + mode.toString() + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, mode.getCode()); } @Override public boolean hasImpactOnMediaList() { return false; } /* * Denon control protocol */ private final static String DCP_COMMAND = "MS"; @NonNull public static ArrayList<String> getAcceptedDcpCodes() { return new ArrayList<>(Collections.singletonList(DCP_COMMAND)); } @Nullable public static ListeningModeMsg processDcpMessage(@NonNull String dcpMsg) { final Mode s = (Mode) searchDcpParameter(DCP_COMMAND, dcpMsg, Mode.values()); return s != null ? new ListeningModeMsg(s) : null; } @Nullable @Override public String buildDcpMsg(boolean isQuery) { return DCP_COMMAND + (isQuery ? DCP_MSG_REQ : mode.getDcpCode()); } }
9,490
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
PlayQueueRemoveMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/PlayQueueRemoveMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import android.annotation.SuppressLint; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /* * Remove from PlayQueue List (from Network Control Only) */ public class PlayQueueRemoveMsg extends ISCPMessage { final static String CODE = "PQR"; // Remove Type: 0:Specify Line, (1:ALL) private final int type; // The Index number in the PlayQueue of the item to delete(0000-FFFF : 1st to 65536th Item [4 HEX digits] ) private final int itemIndex; PlayQueueRemoveMsg(EISCPMessage raw) throws Exception { super(raw); type = Integer.parseInt(data.substring(0, 1), 10); itemIndex = Integer.parseInt(data.substring(1), 16); } public PlayQueueRemoveMsg(final int type, final int itemIndex) { super(0, null); this.type = type; this.itemIndex = itemIndex; } @NonNull @Override public String toString() { return CODE + "[TYPE=" + type + "; INDEX=" + itemIndex + "]"; } @Override public EISCPMessage getCmdMsg() { final String param = type + String.format("%04x", itemIndex); return new EISCPMessage(CODE, param); } /* * Denon control protocol */ @SuppressLint("DefaultLocale") @Nullable @Override public String buildDcpMsg(boolean isQuery) { switch (type) { case 0: return String.format("heos://player/remove_from_queue?pid=%s&qid=%d", DCP_HEOS_PID, itemIndex); case 1: return String.format("heos://player/clear_queue?pid=%s", DCP_HEOS_PID); } return null; } }
2,443
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
DcpEcoModeMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/DcpEcoModeMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import java.util.ArrayList; import java.util.Collections; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; /* * Denon control protocol - DCP ECO mode */ public class DcpEcoModeMsg extends ISCPMessage { public final static String CODE = "D03"; private final static String DCP_COMMAND = "ECO"; @NonNull public static ArrayList<String> getAcceptedDcpCodes() { return new ArrayList<>(Collections.singletonList(DCP_COMMAND)); } public enum Status implements DcpStringParameterIf { NONE("N/A", R.string.device_two_way_switch_none), OFF("OFF", R.string.device_two_way_switch_off), ON("ON", R.string.device_two_way_switch_on), AUTO("AUTO", R.string.device_two_way_switch_auto); final String code; @StringRes final int descriptionId; Status(final String code, @StringRes final int descriptionId) { this.code = code; this.descriptionId = descriptionId; } public String getCode() { return code; } @NonNull public String getDcpCode() { return code; } @StringRes public int getDescriptionId() { return descriptionId; } } private final Status status; DcpEcoModeMsg(EISCPMessage raw) throws Exception { super(raw); status = (Status) searchParameter(data, Status.values(), Status.NONE); } public DcpEcoModeMsg(Status status) { super(0, null); this.status = status; } public Status getStatus() { return status; } @NonNull @Override public String toString() { return CODE + "[" + status.toString() + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, status.getCode()); } @Override public boolean hasImpactOnMediaList() { return false; } @Nullable public static DcpEcoModeMsg processDcpMessage(@NonNull String dcpMsg) { final Status s = (Status) searchDcpParameter(DCP_COMMAND, dcpMsg, Status.values()); return s != null ? new DcpEcoModeMsg(s) : null; } @Nullable @Override public String buildDcpMsg(boolean isQuery) { return DCP_COMMAND + (isQuery ? DCP_MSG_REQ : status.getDcpCode()); } public static Status toggle(Status s) { switch (s) { case OFF: return Status.AUTO; case AUTO: return Status.ON; case ON: return Status.OFF; default: return Status.NONE; } } }
3,591
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
DCPMessageFactory.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/DCPMessageFactory.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.jayway.jsonpath.JsonPath; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import com.mkulesh.onpc.iscp.MessageChannelDcp; import com.mkulesh.onpc.utils.Logging; import java.util.ArrayList; import java.util.HashSet; import java.util.Map; import java.util.Set; import androidx.annotation.NonNull; import androidx.annotation.Nullable; public class DCPMessageFactory { private int zone = ReceiverInformationMsg.DEFAULT_ACTIVE_ZONE; private final ArrayList<ISCPMessage> messages = new ArrayList<>(); private final Set<String> acceptedCodes = new HashSet<>(); public void prepare(int zone) { this.zone = zone; acceptedCodes.addAll(DcpReceiverInformationMsg.getAcceptedDcpCodes()); acceptedCodes.addAll(FriendlyNameMsg.getAcceptedDcpCodes()); acceptedCodes.addAll(PowerStatusMsg.getAcceptedDcpCodes()); acceptedCodes.addAll(InputSelectorMsg.getAcceptedDcpCodes()); // Tone control acceptedCodes.addAll(MasterVolumeMsg.getAcceptedDcpCodes()); acceptedCodes.addAll(ToneCommandMsg.getAcceptedDcpCodes()); acceptedCodes.addAll(AudioMutingMsg.getAcceptedDcpCodes()); acceptedCodes.addAll(ListeningModeMsg.getAcceptedDcpCodes()); // Tuner acceptedCodes.addAll(DcpTunerModeMsg.getAcceptedDcpCodes()); acceptedCodes.addAll(TuningCommandMsg.getAcceptedDcpCodes()); acceptedCodes.addAll(RadioStationNameMsg.getAcceptedDcpCodes()); acceptedCodes.addAll(PresetCommandMsg.getAcceptedDcpCodes()); acceptedCodes.addAll(PresetMemoryMsg.getAcceptedDcpCodes()); // Settings acceptedCodes.addAll(DimmerLevelMsg.getAcceptedDcpCodes()); acceptedCodes.addAll(SleepSetCommandMsg.getAcceptedDcpCodes()); acceptedCodes.addAll(DcpEcoModeMsg.getAcceptedDcpCodes()); acceptedCodes.addAll(DcpAudioRestorerMsg.getAcceptedDcpCodes()); acceptedCodes.addAll(HdmiCecMsg.getAcceptedDcpCodes()); Logging.info(this, "Accepted DCP codes: " + acceptedCodes); } private void convertDcpMsg(@NonNull String dcpMsg) { addISCPMsg(DcpReceiverInformationMsg.processDcpMessage(dcpMsg)); addISCPMsg(FriendlyNameMsg.processDcpMessage(dcpMsg)); addISCPMsg(PowerStatusMsg.processDcpMessage(dcpMsg)); addISCPMsg(InputSelectorMsg.processDcpMessage(dcpMsg)); // Tone control addISCPMsg(MasterVolumeMsg.processDcpMessage(dcpMsg)); addISCPMsg(ToneCommandMsg.processDcpMessage(dcpMsg)); addISCPMsg(AudioMutingMsg.processDcpMessage(dcpMsg)); addISCPMsg(ListeningModeMsg.processDcpMessage(dcpMsg)); // Tuner addISCPMsg(DcpTunerModeMsg.processDcpMessage(dcpMsg)); addISCPMsg(TuningCommandMsg.processDcpMessage(dcpMsg, zone)); addISCPMsg(RadioStationNameMsg.processDcpMessage(dcpMsg)); addISCPMsg(PresetCommandMsg.processDcpMessage(dcpMsg, zone)); addISCPMsg(PresetMemoryMsg.processDcpMessage(dcpMsg)); // Settings addISCPMsg(DimmerLevelMsg.processDcpMessage(dcpMsg)); addISCPMsg(SleepSetCommandMsg.processDcpMessage(dcpMsg)); addISCPMsg(DcpEcoModeMsg.processDcpMessage(dcpMsg)); addISCPMsg(DcpAudioRestorerMsg.processDcpMessage(dcpMsg)); addISCPMsg(HdmiCecMsg.processDcpMessage(dcpMsg)); } private void convertHeosMsg(@NonNull String heosMsg, @Nullable Integer pid) { try { final String result = JsonPath.read(heosMsg, "$.heos.result"); if (!"success".equals(result)) { final Map<String, String> tokens = ISCPMessage.parseHeosMessage(JsonPath.read(heosMsg, "$.heos.message")); Logging.info(this, "DCP HEOS message ignored due to wrong result: " + tokens); return; } } catch (Exception ex) { // nothing to do } try { final String cmd = JsonPath.read(heosMsg, "$.heos.command"); final Map<String, String> tokens = ISCPMessage.parseHeosMessage(JsonPath.read(heosMsg, "$.heos.message")); final String pidStr = tokens.get("pid"); if (pidStr != null && pid != null && !pid.equals(Integer.valueOf(pidStr))) { Logging.info(this, "Received DCP HEOS message for different device. Ignored"); return; } if (tokens.get("command under process") != null) { return; } addISCPMsg(DcpReceiverInformationMsg.processHeosMessage(cmd, heosMsg)); addISCPMsg(FirmwareUpdateMsg.processHeosMessage(cmd, heosMsg)); addISCPMsg(FriendlyNameMsg.processHeosMessage(cmd, heosMsg)); // Playback addISCPMsg(ArtistNameMsg.processHeosMessage(cmd, heosMsg)); addISCPMsg(AlbumNameMsg.processHeosMessage(cmd, heosMsg)); addISCPMsg(TitleNameMsg.processHeosMessage(cmd, heosMsg)); addISCPMsg(JacketArtMsg.processHeosMessage(cmd, heosMsg)); addISCPMsg(TimeInfoMsg.processHeosMessage(cmd, tokens)); addISCPMsg(PlayStatusMsg.processHeosMessage(cmd, tokens)); addISCPMsg(DcpMediaItemMsg.processHeosMessage(cmd, heosMsg)); // Media list addISCPMsg(DcpMediaContainerMsg.processHeosMessage(cmd, heosMsg, tokens)); addISCPMsg(DcpMediaEventMsg.processHeosMessage(cmd)); addISCPMsg(CustomPopupMsg.processHeosMessage(cmd, tokens)); addISCPMsg(DcpSearchCriteriaMsg.processHeosMessage(cmd, heosMsg, tokens)); } catch (Exception ex) { Logging.info(this, "DCP HEOS error: " + ex.getLocalizedMessage() + ", message=" + heosMsg); } } @NonNull public ArrayList<ISCPMessage> convertInputMsg(@NonNull String dcpMsg, @Nullable Integer pid) { messages.clear(); if (dcpMsg.startsWith(MessageChannelDcp.DCP_HEOS_RESPONSE)) { convertHeosMsg(dcpMsg, pid); } else { if (dcpMsg.startsWith(DcpReceiverInformationMsg.DCP_COMMAND_PRESET)) { // Process corner case: OPTPN has some time no end of message symbol // and, therefore, some messages can be joined in one string. // We need to split it before processing dcpMsg = splitJoinedMessages(dcpMsg); } convertDcpMsg(dcpMsg); } return messages; } @NonNull private String splitJoinedMessages(@NonNull String dcpMsg) { int startIndex = dcpMsg.length(); while (true) { int maxIndex = 0; for (String code : acceptedCodes) { maxIndex = Math.max(maxIndex, dcpMsg.lastIndexOf(code, startIndex)); } if (maxIndex > 0) { Logging.info(this, "DCP warning: detected message in the middle: " + dcpMsg + ", start index=" + maxIndex); final String first = dcpMsg.substring(0, maxIndex); final String second = dcpMsg.substring(maxIndex); final int oldSize = messages.size(); convertDcpMsg(second); if (oldSize != messages.size()) { dcpMsg = first; Logging.info(this, "DCP warning: split DCP message: " + first + "/" + second); } else { startIndex = maxIndex - 1; } continue; } break; } return dcpMsg; } @NonNull public ArrayList<String> convertOutputMsg(@Nullable EISCPMessage raw, final String dest) { ArrayList<String> retValue = new ArrayList<>(); if (raw == null) { return retValue; } try { final String toSend = createISCPMessage(raw).buildDcpMsg(raw.isQuery()); if (toSend == null) { return retValue; } final String[] messages = toSend.split(ISCPMessage.DCP_MSG_SEP); for (String msg : messages) { Logging.info(this, ">> DCP sending: " + raw + " => " + msg + " to " + dest); retValue.add(msg); } return retValue; } catch (Exception e) { Logging.info(this, ">> DCP sending error: " + e.getLocalizedMessage()); return retValue; } } private void addISCPMsg(@Nullable ISCPMessage msg) { if (msg != null) { if (messages.isEmpty()) { messages.add(msg); } else { messages.add(0, msg); } } } private ISCPMessage createISCPMessage(EISCPMessage raw) throws Exception { switch (raw.getCode().toUpperCase()) { case FriendlyNameMsg.CODE: return new FriendlyNameMsg(raw); case PowerStatusMsg.CODE: case PowerStatusMsg.ZONE2_CODE: case PowerStatusMsg.ZONE3_CODE: case PowerStatusMsg.ZONE4_CODE: return new PowerStatusMsg(raw); case InputSelectorMsg.CODE: case InputSelectorMsg.ZONE2_CODE: case InputSelectorMsg.ZONE3_CODE: case InputSelectorMsg.ZONE4_CODE: return new InputSelectorMsg(raw); case TimeInfoMsg.CODE: return new TimeInfoMsg(raw); case JacketArtMsg.CODE: return new JacketArtMsg(raw); case TitleNameMsg.CODE: return new TitleNameMsg(raw); case AlbumNameMsg.CODE: return new AlbumNameMsg(raw); case ArtistNameMsg.CODE: return new ArtistNameMsg(raw); case PlayStatusMsg.CODE: case PlayStatusMsg.CD_CODE: return new PlayStatusMsg(raw); case DimmerLevelMsg.CODE: return new DimmerLevelMsg(raw); case AudioMutingMsg.CODE: case AudioMutingMsg.ZONE2_CODE: case AudioMutingMsg.ZONE3_CODE: case AudioMutingMsg.ZONE4_CODE: return new AudioMutingMsg(raw); case MasterVolumeMsg.CODE: case MasterVolumeMsg.ZONE2_CODE: case MasterVolumeMsg.ZONE3_CODE: case MasterVolumeMsg.ZONE4_CODE: return new MasterVolumeMsg(raw); case ToneCommandMsg.CODE: case ToneCommandMsg.ZONE2_CODE: case ToneCommandMsg.ZONE3_CODE: return new ToneCommandMsg(raw); case PresetCommandMsg.CODE: case PresetCommandMsg.ZONE2_CODE: case PresetCommandMsg.ZONE3_CODE: case PresetCommandMsg.ZONE4_CODE: return new PresetCommandMsg(raw); case RadioStationNameMsg.CODE: return new RadioStationNameMsg(raw); case PresetMemoryMsg.CODE: return new PresetMemoryMsg(raw); case TuningCommandMsg.CODE: case TuningCommandMsg.ZONE2_CODE: case TuningCommandMsg.ZONE3_CODE: case TuningCommandMsg.ZONE4_CODE: return new TuningCommandMsg(raw); case ListeningModeMsg.CODE: return new ListeningModeMsg(raw); case HdmiCecMsg.CODE: return new HdmiCecMsg(raw); case SleepSetCommandMsg.CODE: return new SleepSetCommandMsg(raw); case PlayQueueRemoveMsg.CODE: return new PlayQueueRemoveMsg(raw); case PlayQueueReorderMsg.CODE: return new PlayQueueReorderMsg(raw); case FirmwareUpdateMsg.CODE: return new FirmwareUpdateMsg(raw); // Denon control protocol case OperationCommandMsg.CODE: case OperationCommandMsg.ZONE2_CODE: case OperationCommandMsg.ZONE3_CODE: case OperationCommandMsg.ZONE4_CODE: return new OperationCommandMsg(raw); case SetupOperationCommandMsg.CODE: return new SetupOperationCommandMsg(raw); case NetworkServiceMsg.CODE: return new NetworkServiceMsg(raw); case DcpSearchCriteriaMsg.CODE: return new DcpSearchCriteriaMsg(raw); case DcpSearchMsg.CODE: return new DcpSearchMsg(raw); case DcpReceiverInformationMsg.CODE: return new DcpReceiverInformationMsg(raw); case DcpTunerModeMsg.CODE: return new DcpTunerModeMsg(raw); case DcpEcoModeMsg.CODE: return new DcpEcoModeMsg(raw); case DcpAudioRestorerMsg.CODE: return new DcpAudioRestorerMsg(raw); case DcpMediaContainerMsg.CODE: return new DcpMediaContainerMsg(raw); case DcpMediaItemMsg.CODE: return new DcpMediaItemMsg(raw); default: throw new Exception("No factory method for message " + raw.getCode()); } } }
13,792
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
OperationCommandMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/OperationCommandMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.ConnectionIf; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ZonedMessage; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; /* * Network/USB Operation Command (Network Model Only after TX-NR905) */ public class OperationCommandMsg extends ZonedMessage { public final static String CODE = "NTC"; public final static String ZONE2_CODE = "NTZ"; public final static String ZONE3_CODE = "NT3"; public final static String ZONE4_CODE = "NT4"; private final static String[] ZONE_COMMANDS = new String[]{ CODE, ZONE2_CODE, ZONE3_CODE, ZONE4_CODE }; public enum Command implements StringParameterIf { PLAY("PLAY", R.string.cmd_description_play, R.drawable.cmd_play), STOP("STOP", R.string.cmd_description_stop, R.drawable.cmd_stop), PAUSE("PAUSE", R.string.cmd_description_pause, R.drawable.cmd_pause), P_P("P/P", R.string.cmd_description_p_p), TRUP("TRUP", R.string.cmd_description_trup, R.drawable.cmd_next), TRDN("TRDN", R.string.cmd_description_trdn, R.drawable.cmd_previous), FF("FF", R.string.cmd_description_ff, R.drawable.cmd_fast_forward), REW("REW", R.string.cmd_description_rew, R.drawable.cmd_fast_backward), REPEAT("REPEAT", R.string.cmd_description_repeat, R.drawable.repeat_all), RANDOM("RANDOM", R.string.cmd_description_random, R.drawable.cmd_random), REP_SHF("REP/SHF", R.string.cmd_description_rep_shf), DISPLAY("DISPLAY", R.string.cmd_description_display), ALBUM("ALBUM", R.string.cmd_description_album), ARTIST("ARTIST", R.string.cmd_description_artist), GENRE("GENRE", R.string.cmd_description_genre), PLAYLIST("PLAYLIST", R.string.cmd_description_playlist), RIGHT("RIGHT", R.string.cmd_description_right, R.drawable.cmd_right), LEFT("LEFT", R.string.cmd_description_left, R.drawable.cmd_left), UP("UP", R.string.cmd_description_up, R.drawable.cmd_up), DOWN("DOWN", R.string.cmd_description_down, R.drawable.cmd_down), SELECT("SELECT", R.string.cmd_description_select, R.drawable.cmd_select), KEY_0("0", R.string.cmd_description_key_0), KEY_1("1", R.string.cmd_description_key_1), KEY_2("2", R.string.cmd_description_key_2), KEY_3("3", R.string.cmd_description_key_3), KEY_4("4", R.string.cmd_description_key_4), KEY_5("5", R.string.cmd_description_key_5), KEY_6("6", R.string.cmd_description_key_6), KEY_7("7", R.string.cmd_description_key_7), KEY_8("8", R.string.cmd_description_key_8), KEY_9("9", R.string.cmd_description_key_9), DELETE("DELETE", R.string.cmd_description_delete, R.drawable.cmd_delete), CAPS("CAPS", R.string.cmd_description_caps), LOCATION("LOCATION", R.string.cmd_description_location), LANGUAGE("LANGUAGE", R.string.cmd_description_language), SETUP("SETUP", R.string.cmd_description_setup, R.drawable.cmd_setup), RETURN("RETURN", R.string.cmd_description_return, R.drawable.cmd_return), CHUP("CHUP", R.string.cmd_description_chup), CHDN("CHDN", R.string.cmd_description_chdn), MENU("MENU", R.string.cmd_description_menu, R.drawable.cmd_track_menu), TOP("TOP", R.string.cmd_description_top, R.drawable.cmd_top), MODE("MODE", R.string.cmd_description_mode), LIST("LIST", R.string.cmd_description_list), MEMORY("MEMORY", R.string.cmd_description_memory), F1("F1", R.string.cmd_description_f1, R.drawable.feed_like), F2("F2", R.string.cmd_description_f2, R.drawable.feed_dont_like), SORT("SORT", R.string.cmd_description_sort, R.drawable.cmd_sort), /* * Denon control protocol */ DCP_REPEAT_ALL("DCP_REPEAT_ALL", R.string.cmd_description_repeat, R.drawable.repeat_all), DCP_REPEAT_ONE("DCP_REPEAT_ONE", R.string.cmd_description_repeat, R.drawable.repeat_all), DCP_REPEAT_OFF("DCP_REPEAT_OFF", R.string.cmd_description_repeat, R.drawable.repeat_all), DCP_SHUFFLE_ON("DCP_SHUFFLE_ON", R.string.cmd_description_random, R.drawable.cmd_random), DCP_SHUFFLE_OFF("DCP_SHUFFLE_OFF", R.string.cmd_description_random, R.drawable.cmd_random); final String code; @StringRes final int descriptionId; @DrawableRes final int imageId; Command(final String code, @StringRes final int descriptionId) { this.code = code; this.descriptionId = descriptionId; this.imageId = -1; } Command(final String code, @StringRes final int descriptionId, @DrawableRes final int imageId) { this.code = code; this.descriptionId = descriptionId; this.imageId = imageId; } public String getCode() { return code; } @StringRes public int getDescriptionId() { return descriptionId; } @DrawableRes public int getImageId() { return imageId; } public boolean isImageValid() { return imageId != -1; } } private final Command command; OperationCommandMsg(EISCPMessage raw) throws Exception { super(raw, ZONE_COMMANDS); this.command = (Command) searchParameter(data, Command.values(), null); } public OperationCommandMsg(int zoneIndex, final String command) { super(0, null, zoneIndex); this.command = (Command) searchParameter(command, Command.values(), null); } public OperationCommandMsg(final Command command) { super(0, null, ReceiverInformationMsg.DEFAULT_ACTIVE_ZONE); this.command = command; } @Override public String getZoneCommand() { return ZONE_COMMANDS[zoneIndex]; } public Command getCommand() { return command; } @NonNull @Override public String toString() { return getZoneCommand() + "[" + data + "; ZONE_INDEX=" + zoneIndex + "; CMD=" + (command == null ? "null" : command.toString()) + "]"; } @Override public EISCPMessage getCmdMsg() { return command == null ? null : new EISCPMessage(getZoneCommand(), command.getCode()); } @Override public boolean hasImpactOnMediaList() { switch (command) { case REPEAT: case RANDOM: case F1: case F2: return false; default: return true; } } /* * Denon control protocol * - Set Play State Command: heos://player/set_play_state?pid=player_id&state=play_state * - Play Next Command: heos://player/play_next?pid=player_id * - Play Previous Command: heos://player/play_previous?pid=player_id * - Set Play Mode Command: heos://player/set_play_mode?pid='player_id'&repeat=on_all_or_on_one_or_off&shuffle=on_or_off * - Get Music Sources Command: heos://browse/get_music_sources */ @Nullable @Override public String buildDcpMsg(boolean isQuery) { switch (command) { case PLAY: case PAUSE: case STOP: return "heos://player/set_play_state?pid=" + DCP_HEOS_PID + "&state=" + command.name().toLowerCase(); case TRDN: return "heos://player/play_previous?pid=" + DCP_HEOS_PID; case TRUP: return "heos://player/play_next?pid=" + DCP_HEOS_PID; case DCP_REPEAT_ALL: return "heos://player/set_play_mode?pid=" + DCP_HEOS_PID + "&repeat=on_all"; case DCP_REPEAT_ONE: return "heos://player/set_play_mode?pid=" + DCP_HEOS_PID + "&repeat=on_one"; case DCP_REPEAT_OFF: return "heos://player/set_play_mode?pid=" + DCP_HEOS_PID + "&repeat=off"; case DCP_SHUFFLE_ON: return "heos://player/set_play_mode?pid=" + DCP_HEOS_PID + "&shuffle=on"; case DCP_SHUFFLE_OFF: return "heos://player/set_play_mode?pid=" + DCP_HEOS_PID + "&shuffle=off"; case TOP: case RETURN: return "heos://browse/get_music_sources"; } return null; } public static Command toggleRepeat(ProtoType protoType, PlayStatusMsg.RepeatStatus repeatStatus) { if (protoType == ConnectionIf.ProtoType.ISCP) { return Command.REPEAT; } else { switch (repeatStatus) { case OFF: return Command.DCP_REPEAT_ALL; case ALL: return Command.DCP_REPEAT_ONE; default: return Command.DCP_REPEAT_OFF; } } } public static Command toggleShuffle(ProtoType protoType, PlayStatusMsg.ShuffleStatus shuffleStatus) { if (protoType == ConnectionIf.ProtoType.ISCP) { return Command.RANDOM; } else { return shuffleStatus == PlayStatusMsg.ShuffleStatus.OFF ? Command.DCP_SHUFFLE_ON : Command.DCP_SHUFFLE_OFF; } } }
10,110
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
TimeSeekMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/TimeSeekMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import android.annotation.SuppressLint; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; /* * NET/USB Time Seek */ public class TimeSeekMsg extends ISCPMessage { private final static String CODE = "NTS"; private enum TimeFormat { MM60_SS, /* MM60 here minutes between 0 and 59 */ MM99_SS, /* MM99 here minutes between 0 and 99, like for CR-N765 */ HH_MM_SS } private final TimeFormat timeFormat; private final int hours, minutes, seconds; public TimeSeekMsg(final String model, final int hours, final int minutes, final int seconds) { super(0, null); switch (model) { case "CR-N765": timeFormat = TimeFormat.MM99_SS; break; case "NT-503": timeFormat = hours > 0 ? TimeFormat.HH_MM_SS : TimeFormat.MM60_SS; break; default: timeFormat = TimeFormat.HH_MM_SS; break; } this.hours = hours; this.minutes = minutes; this.seconds = seconds; } @NonNull @Override public String toString() { return CODE + "[" + getTimeAsString() + ", FORMAT=" + timeFormat.toString() + "]"; } @SuppressLint("DefaultLocale") public String getTimeAsString() { int MM99_MAX_MIN = 99; switch (timeFormat) { case MM60_SS: return String.format("%02d", minutes) + ":" + String.format("%02d", seconds); case MM99_SS: return String.format("%02d", Math.min(MM99_MAX_MIN, 60 * hours + minutes)) + ":" + String.format("%02d", seconds); case HH_MM_SS: /* it is also default case*/ default: return String.format("%02d", hours) + ":" + String.format("%02d", minutes) + ":" + String.format("%02d", seconds); } } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, getTimeAsString()); } @Override public boolean hasImpactOnMediaList() { return false; } }
2,915
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
InputSelectorMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/InputSelectorMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.ConnectionIf; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ZonedMessage; import java.util.ArrayList; import java.util.Arrays; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; /* * Input Selector Command */ public class InputSelectorMsg extends ZonedMessage { public final static String CODE = "SLI"; final static String ZONE2_CODE = "SLZ"; final static String ZONE3_CODE = "SL3"; final static String ZONE4_CODE = "SL4"; public final static String[] ZONE_COMMANDS = new String[]{ CODE, ZONE2_CODE, ZONE3_CODE, ZONE4_CODE }; public enum InputType implements DcpStringParameterIf { // Integra VIDEO1("00", R.string.input_selector_vcr_dvr, R.drawable.media_item_vhs), VIDEO2("01", R.string.input_selector_cbl_sat, R.drawable.media_item_sat), VIDEO3("02", R.string.input_selector_game, R.drawable.media_item_game), VIDEO4("03", R.string.input_selector_aux, R.drawable.media_item_aux), VIDEO5("04", R.string.input_selector_aux2, R.drawable.media_item_aux), VIDEO6("05", R.string.input_selector_pc, R.drawable.media_item_pc), VIDEO7("06", R.string.input_selector_video7, R.drawable.media_item_hdmi), EXTRA1("07", R.string.input_selector_extra1, R.drawable.media_item_hdmi), EXTRA2("08", R.string.input_selector_extra2, R.drawable.media_item_hdmi), BD_DVD("10", R.string.input_selector_bd_dvd, R.drawable.media_item_disc_player), STRM_BOX("11", R.string.input_selector_strm_box, R.drawable.media_item_mplayer), TV("12", R.string.input_selector_tv, R.drawable.media_item_tv), TAPE1("20", R.string.input_selector_tape1, R.drawable.media_item_tape), TAPE2("21", R.string.input_selector_tape2, R.drawable.media_item_tape), PHONO("22", R.string.input_selector_phono, R.drawable.media_item_phono), CD("23", R.string.input_selector_cd, R.drawable.media_item_disc_player), FM("24", R.string.input_selector_fm, R.drawable.media_item_radio_fm), AM("25", R.string.input_selector_am, R.drawable.media_item_radio_am), TUNER("26", R.string.input_selector_tuner, R.drawable.media_item_radio), MUSIC_SERVER("27", R.string.input_selector_music_server, R.drawable.media_item_media_server, true), INTERNET_RADIO("28", R.string.input_selector_internet_radio, R.drawable.media_item_radio_digital), USB_FRONT("29", R.string.input_selector_usb_front, R.drawable.media_item_usb, true), USB_REAR("2A", R.string.input_selector_usb_rear, R.drawable.media_item_usb, true), NET("2B", R.string.input_selector_net, R.drawable.media_item_net, true), USB_TOGGLE("2C", R.string.input_selector_usb_toggle, R.drawable.media_item_usb), AIRPLAY("2D", R.string.input_selector_airplay, R.drawable.media_item_airplay), BLUETOOTH("2E", R.string.input_selector_bluetooth, R.drawable.media_item_bluetooth), USB_DAC_IN("2F", R.string.input_selector_usb_dac_in, R.drawable.media_item_usb), LINE("41", R.string.input_selector_line, R.drawable.media_item_rca), LINE2("42", R.string.input_selector_line2, R.drawable.media_item_rca), OPTICAL("44", R.string.input_selector_optical, R.drawable.media_item_toslink), COAXIAL("45", R.string.input_selector_coaxial), UNIVERSAL_PORT("40", R.string.input_selector_universal_port), MULTI_CH("30", R.string.input_selector_multi_ch), XM("31", R.string.input_selector_xm), SIRIUS("32", R.string.input_selector_sirius), DAB("33", R.string.input_selector_dab, R.drawable.media_item_radio_dab), HDMI_5("55", R.string.input_selector_hdmi_5, R.drawable.media_item_hdmi), HDMI_6("56", R.string.input_selector_hdmi_6, R.drawable.media_item_hdmi), HDMI_7("57", R.string.input_selector_hdmi_7, R.drawable.media_item_hdmi), SOURCE("80", R.string.input_selector_source, R.drawable.media_item_source), // Denon DCP_PHONO("PHONO", R.string.input_selector_phono, R.drawable.media_item_phono), DCP_CD("CD", R.string.input_selector_cd, R.drawable.media_item_disc_player), DCP_DVD("DVD", R.string.input_selector_dvd, R.drawable.media_item_disc_player), DCP_BD("BD", R.string.input_selector_bd, R.drawable.media_item_disc_player), DCP_TV("TV", R.string.input_selector_tv, R.drawable.media_item_tv), DCP_SAT_CBL("SAT/CBL", R.string.input_selector_cbl_sat, R.drawable.media_item_sat), DCP_MPLAY("MPLAY", R.string.input_selector_mplayer, R.drawable.media_item_mplayer), DCP_GAME("GAME", R.string.input_selector_game, R.drawable.media_item_game), DCP_TUNER("TUNER", R.string.input_selector_tuner, R.drawable.media_item_radio), DCP_AUX1("AUX1", R.string.input_selector_aux1, R.drawable.media_item_rca), DCP_AUX2("AUX2", R.string.input_selector_aux2, R.drawable.media_item_rca), DCP_AUX3("AUX3", R.string.input_selector_aux3, R.drawable.media_item_rca), DCP_AUX4("AUX4", R.string.input_selector_aux4, R.drawable.media_item_rca), DCP_AUX5("AUX5", R.string.input_selector_aux5, R.drawable.media_item_rca), DCP_AUX6("AUX6", R.string.input_selector_aux6, R.drawable.media_item_rca), DCP_AUX7("AUX7", R.string.input_selector_aux7, R.drawable.media_item_rca), DCP_NET("NET", R.string.input_selector_net, R.drawable.media_item_net, true), DCP_BT("BT", R.string.input_selector_bluetooth, R.drawable.media_item_bluetooth), DCP_SOURCE("SOURCE", R.string.input_selector_source, R.drawable.media_item_source), NONE("XX", -1); final String code; @StringRes final int descriptionId; @DrawableRes final int imageId; final boolean mediaList; @SuppressWarnings("SameParameterValue") InputType(String code, @StringRes final int descriptionId, @DrawableRes final int imageId, final boolean mediaList) { this.code = code; this.descriptionId = descriptionId; this.imageId = imageId; this.mediaList = mediaList; } InputType(String code, @StringRes final int descriptionId, @DrawableRes final int imageId) { this.code = code; this.descriptionId = descriptionId; this.imageId = imageId; this.mediaList = false; } InputType(String code, @StringRes final int descriptionId) { this.code = code; this.descriptionId = descriptionId; this.imageId = R.drawable.media_item_unknown; this.mediaList = false; } public ProtoType getProtoType() { return name().startsWith("DCP_") ? ConnectionIf.ProtoType.DCP : ConnectionIf.ProtoType.ISCP; } public String getCode() { return code; } @NonNull public String getDcpCode() { return name().startsWith("DCP_") ? code : "XX"; } @StringRes public int getDescriptionId() { return descriptionId; } @DrawableRes public int getImageId() { return imageId; } public boolean isMediaList() { return mediaList; } } private final InputType inputType; InputSelectorMsg(EISCPMessage raw) throws Exception { super(raw, ZONE_COMMANDS); inputType = (InputType) searchParameter(data, InputType.values(), InputType.NONE); } public InputSelectorMsg(int zoneIndex, final String cmd) { super(0, null, zoneIndex); inputType = (InputType) searchParameter(cmd, InputType.values(), InputType.NONE); } @Override public String getZoneCommand() { return ZONE_COMMANDS[zoneIndex]; } public InputType getInputType() { return inputType; } @NonNull @Override public String toString() { return getZoneCommand() + "[" + data + "; ZONE_INDEX=" + zoneIndex + "; INPUT_TYPE=" + inputType.toString() + "; CODE=" + inputType.getCode() + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(getZoneCommand(), inputType.getCode()); } /* * Denon control protocol */ private final static String[] DCP_COMMANDS = new String[]{ "SI", "Z2", "Z3" }; @NonNull public static ArrayList<String> getAcceptedDcpCodes() { return new ArrayList<>(Arrays.asList(DCP_COMMANDS)); } @Nullable public static InputSelectorMsg processDcpMessage(@NonNull String dcpMsg) { // Only loop over DCP inputs due to conflicts with zone audio volume event for (int i = 0; i < DCP_COMMANDS.length; i++) { final InputType s = (InputType) searchDcpParameter(DCP_COMMANDS[i], dcpMsg, InputType.values()); if (s != null && s != InputType.NONE) { return new InputSelectorMsg(i, s.getCode()); } } return null; } @Nullable @Override public String buildDcpMsg(boolean isQuery) { if (zoneIndex < DCP_COMMANDS.length) { return DCP_COMMANDS[zoneIndex] + (isQuery ? DCP_MSG_REQ : inputType.getDcpCode()); } return null; } }
10,332
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
RDSInformationMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/RDSInformationMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; /* * RDS Information Command (RDS Model Only) */ public class RDSInformationMsg extends ISCPMessage { public final static String CODE = "RDS"; public final static String TOGGLE = "UP"; RDSInformationMsg(EISCPMessage raw) throws Exception { super(raw); } public RDSInformationMsg(String mode) { super(0, mode); } @NonNull @Override public String toString() { return CODE + "[" + data + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, data); } @Override public boolean hasImpactOnMediaList() { return false; } }
1,511
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
DirectCommandMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/DirectCommandMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /* * Direct Command */ public class DirectCommandMsg extends ISCPMessage { public final static String CODE = "DIR"; public enum Status implements StringParameterIf { NONE("N/A", R.string.device_two_way_switch_none), OFF("00", R.string.device_two_way_switch_off), ON("01", R.string.device_two_way_switch_on), TOGGLE("TG", R.string.device_two_way_switch_toggle); final String code; @StringRes final int descriptionId; Status(final String code, @StringRes final int descriptionId) { this.code = code; this.descriptionId = descriptionId; } public String getCode() { return code; } @SuppressWarnings("unused") @StringRes public int getDescriptionId() { return descriptionId; } } private final Status status; DirectCommandMsg(EISCPMessage raw) throws Exception { super(raw); status = (Status) searchParameter(data, Status.values(), Status.NONE); } public DirectCommandMsg(Status status) { super(0, null); this.status = status; } public Status getStatus() { return status; } @NonNull @Override public String toString() { return CODE + "[" + status.getCode() + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, status.getCode()); } @Override public boolean hasImpactOnMediaList() { return false; } }
2,504
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
ArtistNameMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/ArtistNameMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.jayway.jsonpath.JsonPath; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /* * NET/USB Artist Name (variable-length, 64 ASCII letters max) */ public class ArtistNameMsg extends ISCPMessage { public final static String CODE = "NAT"; ArtistNameMsg(EISCPMessage raw) throws Exception { super(raw); } ArtistNameMsg(final String name) { super(0, name); } @NonNull @Override public String toString() { return CODE + "[" + data + "]"; } /* * Denon control protocol */ private final static String HEOS_COMMAND = "player/get_now_playing_media"; @Nullable public static ArtistNameMsg processHeosMessage(@NonNull final String command, @NonNull final String heosMsg) { if (HEOS_COMMAND.equals(command)) { final String name = JsonPath.read(heosMsg, "$.payload.artist"); return new ArtistNameMsg(name); } return null; } }
1,814
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
CustomPopupMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/CustomPopupMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import java.util.Map; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /* * NET Custom Popup Message (for Network Control Only) */ public class CustomPopupMsg extends ISCPMessage { public final static String CODE = "NCP"; /* * UI Type * 0 : List, 1 : Menu, 2 : Playback, 3 : Popup, 4 : Keyboard, 5 : Menu List */ public enum UiType implements CharParameterIf { XML('X'), LIST('0'), MENU('1'), PLAYBACK('2'), POPUP('3'), KEYBOARD('4'), MENU_LIST('5'); final Character code; UiType(Character code) { this.code = code; } public Character getCode() { return code; } } private final UiType uiType; private final String xml; CustomPopupMsg(EISCPMessage raw) throws Exception { super(raw); uiType = (UiType) searchParameter(data.charAt(0), UiType.values(), UiType.XML); xml = data.substring(1); } public CustomPopupMsg(final UiType uiType, final String xml) { super(0, uiType.getCode() + "000" + xml); this.uiType = uiType; this.xml = xml; } public String getXml() { return xml; } @NonNull @Override public String toString() { return CODE + "[" + uiType.toString() + "; " + (isMultiline() ? ("XML<" + xml.length() + "B>") : ("XML=" + xml)) + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, data); } /* * Denon control protocol - Player Playback Error */ private final static String HEOS_COMMAND = "event/player_playback_error"; @Nullable public static CustomPopupMsg processHeosMessage(@NonNull final String command, @NonNull final Map<String, String> tokens) { if (HEOS_COMMAND.equals(command)) { final String error = tokens.get("error"); if (error != null) { final String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<popup title=\"Error\">" + "<label title=\"\"><line text=\"" + error + "\"/></label></popup>"; return new CustomPopupMsg(UiType.XML, xml); } } return null; } }
3,155
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
AutoPowerMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/AutoPowerMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /* * Auto Power Command */ public class AutoPowerMsg extends ISCPMessage { public final static String CODE = "APD"; public enum Status implements StringParameterIf { NONE("N/A", R.string.device_two_way_switch_none), OFF("00", R.string.device_two_way_switch_off), ON("01", R.string.device_two_way_switch_on), TOGGLE("UP", R.string.device_two_way_switch_toggle); final String code; @StringRes final int descriptionId; Status(final String code, @StringRes final int descriptionId) { this.code = code; this.descriptionId = descriptionId; } public String getCode() { return code; } @StringRes public int getDescriptionId() { return descriptionId; } } private final Status status; AutoPowerMsg(EISCPMessage raw) throws Exception { super(raw); status = (Status) searchParameter(data, Status.values(), Status.NONE); } public AutoPowerMsg(Status level) { super(0, null); this.status = level; } public Status getStatus() { return status; } @NonNull @Override public String toString() { return CODE + "[" + status.toString() + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, status.getCode()); } @Override public boolean hasImpactOnMediaList() { return false; } }
2,459
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
SpeakerBCommandMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/SpeakerBCommandMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ZonedMessage; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /* * Speaker B Command (For Main zone and Zone 2 only) */ public class SpeakerBCommandMsg extends ZonedMessage { final static String CODE = "SPB"; final static String ZONE2_CODE = "ZPB"; public final static String[] ZONE_COMMANDS = new String[]{ CODE, ZONE2_CODE, CODE, CODE }; public enum Status implements StringParameterIf { NONE("N/A", R.string.device_two_way_switch_none), OFF("00", R.string.device_two_way_switch_off), ON("01", R.string.device_two_way_switch_on), TOGGLE("UP", R.string.speaker_b_command_toggle); /* Only available for main zone */ final String code; @StringRes final int descriptionId; Status(final String code, @StringRes final int descriptionId) { this.code = code; this.descriptionId = descriptionId; } public String getCode() { return code; } @SuppressWarnings("unused") @StringRes public int getDescriptionId() { return descriptionId; } } private final Status status; SpeakerBCommandMsg(EISCPMessage raw) throws Exception { super(raw, ZONE_COMMANDS); status = (Status) searchParameter(data, Status.values(), Status.NONE); } public SpeakerBCommandMsg(int zoneIndex, Status level) { super(0, null, zoneIndex); this.status = level; } @Override public String getZoneCommand() { return ZONE_COMMANDS[zoneIndex]; } public Status getStatus() { return status; } @NonNull @Override public String toString() { return getZoneCommand() + "[" + data + "; ZONE_INDEX=" + zoneIndex + "; STATUS=" + status.toString() + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(getZoneCommand(), status.getCode()); } @Override public boolean hasImpactOnMediaList() { return false; } }
2,961
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
HdmiCecMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/HdmiCecMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.ConnectionIf; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import java.util.ArrayList; import java.util.Collections; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; /* * HDMI CEC settings */ public class HdmiCecMsg extends ISCPMessage { public final static String CODE = "CEC"; public enum Status implements DcpStringParameterIf { NONE("N/A", R.string.device_two_way_switch_none), OFF("00", R.string.device_two_way_switch_off), ON("01", R.string.device_two_way_switch_on), TOGGLE("UP", R.string.device_two_way_switch_toggle); final String code; @StringRes final int descriptionId; Status(final String code, @StringRes final int descriptionId) { this.code = code; this.descriptionId = descriptionId; } public String getCode() { return code; } @NonNull public String getDcpCode() { return name(); } @StringRes public int getDescriptionId() { return descriptionId; } } private final Status status; HdmiCecMsg(EISCPMessage raw) throws Exception { super(raw); status = (Status) searchParameter(data, Status.values(), Status.NONE); } public HdmiCecMsg(Status level) { super(0, null); this.status = level; } public Status getStatus() { return status; } @NonNull @Override public String toString() { return CODE + "[" + status.toString() + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, status.getCode()); } @Override public boolean hasImpactOnMediaList() { return false; } public static Status toggle(Status s, ProtoType proto) { return proto == ConnectionIf.ProtoType.ISCP ? Status.TOGGLE : ((s == Status.OFF) ? Status.ON : Status.OFF); } /* * Denon control protocol */ private final static String DCP_COMMAND = "SSHOS"; private final static String DCP_COMMAND_EXT = "CON"; @NonNull public static ArrayList<String> getAcceptedDcpCodes() { return new ArrayList<>(Collections.singletonList(DCP_COMMAND)); } @Nullable public static HdmiCecMsg processDcpMessage(@NonNull String dcpMsg) { final Status s = (Status) searchDcpParameter( DCP_COMMAND + DCP_COMMAND_EXT, dcpMsg, Status.values()); return s != null ? new HdmiCecMsg(s) : null; } @Nullable @Override public String buildDcpMsg(boolean isQuery) { // A space is needed for this command return DCP_COMMAND + (isQuery ? (" " + DCP_MSG_REQ) : DCP_COMMAND_EXT + " " + status.getDcpCode()); } }
3,748
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
ListItemInfoMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/ListItemInfoMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; /* * NET/USB List Info (Update item, need processing XML data, for Network Control Only) */ public class ListItemInfoMsg extends ISCPMessage { public final static String CODE = "NLU"; private final int index, number; ListItemInfoMsg(EISCPMessage raw) throws Exception { super(raw); index = Integer.parseInt(data.substring(0, 4), 16); number = Integer.parseInt(data.substring(4, 8), 16); } @NonNull @Override public String toString() { return CODE + "[" + data + "; " + index + "/" + number + "]"; } }
1,415
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
AmpOperationCommandMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/AmpOperationCommandMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /* * Amplifier Operation Command */ public class AmpOperationCommandMsg extends ISCPMessage { public final static String CODE = "CAP"; public enum Command implements StringParameterIf { MVLUP(R.string.amp_cmd_volume_up, R.drawable.volume_amp_up), MVLDOWN(R.string.amp_cmd_volume_down, R.drawable.volume_amp_down), SLIUP(R.string.amp_cmd_selector_up, R.drawable.input_selector_up), SLIDOWN(R.string.amp_cmd_selector_down, R.drawable.input_selector_down), AMTON(R.string.amp_cmd_audio_muting_on, R.drawable.volume_amp_muting), AMTOFF(R.string.amp_cmd_audio_muting_off, R.drawable.volume_amp_muting), AMTTG(R.string.amp_cmd_audio_muting_toggle, R.drawable.volume_amp_muting), PWRON(R.string.amp_cmd_system_on, R.drawable.menu_power_standby), PWROFF(R.string.amp_cmd_system_standby, R.drawable.menu_power_standby), PWRTG(R.string.amp_cmd_system_on_toggle, R.drawable.menu_power_standby); @StringRes final int descriptionId; @DrawableRes final int imageId; Command(@StringRes final int descriptionId, @DrawableRes final int imageId) { this.descriptionId = descriptionId; this.imageId = imageId; } public String getCode() { return toString(); } @StringRes public int getDescriptionId() { return descriptionId; } @DrawableRes public int getImageId() { return imageId; } } private final Command command; public AmpOperationCommandMsg(final String command) { super(0, null); this.command = (Command) searchParameter(command, Command.values(), null); } public Command getCommand() { return command; } @NonNull @Override public String toString() { return CODE + "[" + (command == null ? "null" : command.toString()) + "]"; } @Override public EISCPMessage getCmdMsg() { return command == null ? null : new EISCPMessage(CODE, command.getCode()); } @Override public boolean hasImpactOnMediaList() { return false; } }
3,188
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
PhaseMatchingBassMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/PhaseMatchingBassMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /* * Phase Matching Bass Command */ public class PhaseMatchingBassMsg extends ISCPMessage { public final static String CODE = "PMB"; public enum Status implements StringParameterIf { NONE("N/A", R.string.device_two_way_switch_none), OFF("00", R.string.device_two_way_switch_off), ON("01", R.string.device_two_way_switch_on), TOGGLE("TG", R.string.device_two_way_switch_toggle); final String code; @StringRes final int descriptionId; Status(final String code, @StringRes final int descriptionId) { this.code = code; this.descriptionId = descriptionId; } public String getCode() { return code; } @StringRes public int getDescriptionId() { return descriptionId; } } private final Status status; PhaseMatchingBassMsg(EISCPMessage raw) throws Exception { super(raw); status = (Status) searchParameter(data, Status.values(), Status.NONE); } public PhaseMatchingBassMsg(Status status) { super(0, null); this.status = status; } public Status getStatus() { return status; } @NonNull @Override public String toString() { return CODE + "[" + status.toString() + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, status.getCode()); } @Override public boolean hasImpactOnMediaList() { return false; } }
2,494
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
PlayQueueAddMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/PlayQueueAddMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; /* * Add PlayQueue List in List View (from Network Control Only) */ public class PlayQueueAddMsg extends ISCPMessage { private final static String CODE = "PQA"; // The Index number of the item to be added in the content list // (0000-FFFF : 1st to 65536th Item [4 HEX digits] ) // It is also possible to set folder. private final int itemIndex; // Add Type: 0:Now, 1:Next, 2:Last private final int type; // The Index number in the PlayQueue to be added(0000-FFFF : 1st to 65536th Item [4 HEX digits] ) private final int targetIndex; public PlayQueueAddMsg(final int itemIndex, final int type) { super(0, null); this.itemIndex = itemIndex; this.type = type; this.targetIndex = 0; } @NonNull @Override public String toString() { return CODE + "[INDEX=" + itemIndex + "; TYPE=" + type + "]"; } @Override public EISCPMessage getCmdMsg() { final String param = String.format("%04x", itemIndex) + type + String.format("%04x", targetIndex); return new EISCPMessage(CODE, param); } }
1,977
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
ListInfoMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/ListInfoMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; /* * NET/USB List Info */ public class ListInfoMsg extends ISCPMessage { public final static String CODE = "NLS"; /* * Information Type (A : ASCII letter, C : Cursor Info, U : Unicode letter) */ public enum InformationType implements CharParameterIf { ASCII('A'), CURSOR('C'), UNICODE('U'); final Character code; InformationType(Character code) { this.code = code; } public Character getCode() { return code; } } private InformationType informationType = InformationType.CURSOR; /* Line Info (0-9 : 1st to 10th Line) */ private final int lineInfo; /* * Property * - : no * 0 : Playing, A : Artist, B : Album, F : Folder, M : Music, P : Playlist, S : Search * a : Account, b : Playlist-C, c : Starred, d : Unstarred, e : What's New */ private enum Property implements CharParameterIf { NO('-'), PLAYING('0'), ARTIST('A'), ALBUM('B'), FOLDER('F'), MUSIC('M'), PLAYLIST('P'), SEARCH('S'), ACCOUNT('A'), PLAYLIST_C('B'), STARRED('C'), UNSTARRED('D'), WHATS_NEW('E'); final Character code; Property(Character code) { this.code = code; } public Character getCode() { return code; } } private Property property = Property.NO; /* * Update Type (P : Page Information Update ( Page Clear or Disable List Info) , C : Cursor Position Update) */ public enum UpdateType implements CharParameterIf { NO('-'), PAGE('P'), CURSOR('C'); final Character code; UpdateType(Character code) { this.code = code; } public Character getCode() { return code; } } private UpdateType updateType = UpdateType.NO; private String listedData = null; ListInfoMsg(EISCPMessage raw) throws Exception { super(raw); informationType = (InformationType) searchParameter(data.charAt(0), InformationType.values(), informationType); final char lineInfoChar = data.charAt(1); lineInfo = Character.isDigit(lineInfoChar) ? Integer.parseInt(String.valueOf(lineInfoChar)) : -1; switch (informationType) { case ASCII: case UNICODE: property = (Property) searchParameter(data.charAt(2), Property.values(), property); listedData = data.substring(3); break; case CURSOR: updateType = (UpdateType) searchParameter(data.charAt(2), UpdateType.values(), updateType); break; } } public ListInfoMsg(final int lineInfo, final String listedData) { super(0, null); informationType = InformationType.UNICODE; this.lineInfo = lineInfo; //noinspection ConstantConditions property = Property.NO; //noinspection ConstantConditions updateType = UpdateType.NO; this.listedData = listedData; } public InformationType getInformationType() { return informationType; } public UpdateType getUpdateType() { return updateType; } public String getListedData() { return listedData; } public int getLineInfo() { return lineInfo; } @NonNull @Override public String toString() { return CODE + "[" + data + "; INF_TYPE=" + informationType.toString() + "; LINE_INFO=" + lineInfo + "; PROPERTY=" + property.toString() + "; UPD_TYPE=" + updateType.toString() + "; LIST_DATA=" + listedData + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, "L" + lineInfo); } }
4,806
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
DcpTunerModeMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/DcpTunerModeMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import java.util.ArrayList; import java.util.Collections; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; /* * Denon control protocol - actual tuner mode */ public class DcpTunerModeMsg extends ISCPMessage { public final static String CODE = "D02"; private final static String DCP_COMMAND = "TMAN"; @NonNull public static ArrayList<String> getAcceptedDcpCodes() { return new ArrayList<>(Collections.singletonList(DCP_COMMAND)); } public enum TunerMode implements DcpStringParameterIf { NONE("N/A", R.string.dashed_string, R.drawable.media_item_unknown), FM("FM", R.string.input_selector_fm, R.drawable.media_item_radio_fm), DAB("DAB", R.string.input_selector_dab, R.drawable.media_item_radio_dab); final String code; @StringRes final int descriptionId; @DrawableRes final int imageId; TunerMode(final String code, @StringRes final int descriptionId, @DrawableRes final int imageId) { this.code = code; this.descriptionId = descriptionId; this.imageId = imageId; } public String getCode() { return code; } @NonNull public String getDcpCode() { return code; } @StringRes public int getDescriptionId() { return descriptionId; } @DrawableRes public int getImageId() { return imageId; } } private final TunerMode tunerMode; DcpTunerModeMsg(EISCPMessage raw) throws Exception { super(raw); tunerMode = (TunerMode) searchParameter(data, TunerMode.values(), TunerMode.NONE); } public DcpTunerModeMsg(TunerMode mode) { super(0, null); this.tunerMode = mode; } public TunerMode getTunerMode() { return tunerMode; } @NonNull @Override public String toString() { return CODE + "[" + tunerMode.toString() + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, tunerMode.getCode()); } @Override public boolean hasImpactOnMediaList() { return false; } @Nullable public static DcpTunerModeMsg processDcpMessage(@NonNull String dcpMsg) { final TunerMode s = (TunerMode) searchDcpParameter(DCP_COMMAND, dcpMsg, TunerMode.values()); return s != null ? new DcpTunerModeMsg(s) : null; } @Nullable @Override public String buildDcpMsg(boolean isQuery) { return DCP_COMMAND + (isQuery ? DCP_MSG_REQ : tunerMode.getDcpCode()); } }
3,639
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
NetworkStandByMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/NetworkStandByMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /* * Network Standby Settings (for Network Control Only and Available in AVR is PowerOn) */ public class NetworkStandByMsg extends ISCPMessage { public final static String CODE = "NSB"; public enum Status implements StringParameterIf { NONE("N/A", R.string.device_two_way_switch_none), OFF("OFF", R.string.device_two_way_switch_off), ON("ON", R.string.device_two_way_switch_on); final String code; @StringRes final int descriptionId; Status(final String code, @StringRes final int descriptionId) { this.code = code; this.descriptionId = descriptionId; } public String getCode() { return code; } @StringRes public int getDescriptionId() { return descriptionId; } } private final Status status; NetworkStandByMsg(EISCPMessage raw) throws Exception { super(raw); status = (Status) searchParameter(data, Status.values(), Status.NONE); } public NetworkStandByMsg(Status level) { super(0, null); this.status = level; } public Status getStatus() { return status; } @NonNull @Override public String toString() { return CODE + "[" + status.toString() + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, status.getCode()); } @Override public boolean hasImpactOnMediaList() { return false; } }
2,479
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
DisplayModeMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/DisplayModeMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; /* * Display Mode Command */ public class DisplayModeMsg extends ISCPMessage { public final static String CODE = "DIF"; public final static String TOGGLE = "TG"; DisplayModeMsg(EISCPMessage raw) throws Exception { super(raw); } public DisplayModeMsg(String mode) { super(0, mode); } @NonNull @Override public String toString() { return CODE + "[" + data + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, data); } @Override public boolean hasImpactOnMediaList() { return false; } }
1,482
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
PlayQueueReorderMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/PlayQueueReorderMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import android.annotation.SuppressLint; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /* * Reorder PlayQueue List (from Network Control Only) */ public class PlayQueueReorderMsg extends ISCPMessage { final static String CODE = "PQO"; // The Index number in the PlayQueue of the item to be moved // (0000-FFFF : 1st to 65536th Item [4 HEX digits] ) . private final int itemIndex; // The Index number in the PlayQueue of destination. // (0000-FFFF : 1st to 65536th Item [4 HEX digits] ) private final int targetIndex; PlayQueueReorderMsg(EISCPMessage raw) throws Exception { super(raw); itemIndex = Integer.parseInt(data.substring(0, 4), 16); targetIndex = Integer.parseInt(data.substring(4), 16); } public PlayQueueReorderMsg(final int itemIndex, final int targetIndex) { super(0, null); this.itemIndex = itemIndex; this.targetIndex = targetIndex; } @NonNull @Override public String toString() { return CODE + "[INDEX=" + itemIndex + "; TARGET=" + targetIndex + "]"; } @Override public EISCPMessage getCmdMsg() { final String param = String.format("%04x", itemIndex) + String.format("%04x", targetIndex); return new EISCPMessage(CODE, param); } /* * Denon control protocol */ @SuppressLint("DefaultLocale") @Nullable @Override public String buildDcpMsg(boolean isQuery) { return String.format("heos://player/move_queue_item?pid=%s&sqid=%d&dqid=%d", DCP_HEOS_PID, itemIndex, targetIndex); } }
2,468
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
DcpSearchCriteriaMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/DcpSearchCriteriaMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.jayway.jsonpath.JsonPath; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import com.mkulesh.onpc.utils.Logging; import java.util.ArrayList; import java.util.List; import java.util.Map; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.util.Pair; /* * Denon control protocol - Get Source Search Criteria * Command: heos://browse/get_searchcriteria?sid=source_id Response: { "heos": { "command": "browse/ get_searchcriteria ", "result": "success", "message": "sid='source_id " }, "payload": [ { "name": "Artist", "scid": "'searchcriteria_id'", "wildcard": "yes_or_no", }, { "name": "Album", "scid": "'searchcriteria_id'", "wildcard": "yes_or_no", }, ... ] } */ public class DcpSearchCriteriaMsg extends ISCPMessage { public final static String CODE = "D08"; private final static String HEOS_COMMAND = "browse/get_search_criteria"; private final String sid; private final List<Pair<String, Integer>> criteria = new ArrayList<>(); DcpSearchCriteriaMsg(EISCPMessage raw) throws Exception { super(raw); sid = getData(); } public DcpSearchCriteriaMsg(final String sid) { super(0, sid); this.sid = sid; } DcpSearchCriteriaMsg(final String sid, List<Pair<String, Integer>> cr) { super(0, sid); this.sid = sid; criteria.addAll(cr); } public String getSid() { return sid; } public List<Pair<String, Integer>> getCriteria() { return criteria; } @NonNull @Override public String toString() { return "DCP search criteria for SID=" + sid + ": " + criteria.toString(); } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, sid); } @Override public boolean hasImpactOnMediaList() { return false; } @Nullable public static DcpSearchCriteriaMsg processHeosMessage(@NonNull final String command, @NonNull final String heosMsg, @NonNull final Map<String, String> tokens) { if (HEOS_COMMAND.equals(command)) { final String sid = tokens.get("sid"); if (sid == null || sid.isEmpty()) { return null; } final List<String> names = JsonPath.read(heosMsg, "$.payload[*].name"); final List<Integer> csids = JsonPath.read(heosMsg, "$.payload[*].scid"); if (names.size() != csids.size()) { Logging.info(DcpReceiverInformationMsg.class, "Inconsistent size of names and csids"); return null; } final List<Pair<String, Integer>> cr = new ArrayList<>(); for (int i = 0; i < names.size(); i++) { if (names.get(i) != null && csids.get(i) != null) { cr.add(new Pair<>(names.get(i), csids.get(i))); } } return new DcpSearchCriteriaMsg(sid, cr); } return null; } @Nullable @Override public String buildDcpMsg(boolean isQuery) { return "heos://" + HEOS_COMMAND + "?sid=" + sid; } }
4,056
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
AlbumNameMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/AlbumNameMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.jayway.jsonpath.JsonPath; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /* * NET/USB Album Name (variable-length, 64 ASCII letters max) */ public class AlbumNameMsg extends ISCPMessage { public final static String CODE = "NAL"; AlbumNameMsg(EISCPMessage raw) throws Exception { super(raw); } AlbumNameMsg(final String name) { super(0, name); } @NonNull @Override public String toString() { return CODE + "[" + data + "]"; } /* * Denon control protocol */ private final static String HEOS_COMMAND = "player/get_now_playing_media"; @Nullable public static AlbumNameMsg processHeosMessage(@NonNull final String command, @NonNull final String heosMsg) { if (HEOS_COMMAND.equals(command)) { final String name = JsonPath.read(heosMsg, "$.payload.album"); return new AlbumNameMsg(name); } return null; } }
1,807
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
ListTitleInfoMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/ListTitleInfoMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; /* * NET/USB List Title Info */ public class ListTitleInfoMsg extends ISCPMessage { public final static String CODE = "NLT"; private ServiceType serviceType = ServiceType.UNKNOWN; /* * UI Type 0 : List, 1 : Menu, 2 : Playback, 3 : Popup, 4 : Keyboard, "5" : Menu List */ public enum UIType implements CharParameterIf { LIST('0'), MENU('1'), PLAYBACK('2'), POPUP('3'), KEYBOARD('4'), MENU_LIST('5'); final Character code; UIType(Character code) { this.code = code; } public Character getCode() { return code; } } private UIType uiType = UIType.LIST; /* * Layer Info : 0 : NET TOP, 1 : Service Top,DLNA/USB/iPod Top, 2 : under 2nd Layer */ public enum LayerInfo implements CharParameterIf { NET_TOP('0'), SERVICE_TOP('1'), UNDER_2ND_LAYER('2'); final Character code; LayerInfo(Character code) { this.code = code; } public Character getCode() { return code; } } private LayerInfo layerInfo = LayerInfo.NET_TOP; /* Current Cursor Position (HEX 4 letters) */ private int currentCursorPosition = 0; /* Number of List Items (HEX 4 letters) */ private int numberOfItems = 0; /* Number of Layer(HEX 2 letters) */ private int numberOfLayers = 0; /* * Start Flag : 0 : Not First, 1 : First */ private enum StartFlag implements CharParameterIf { NOT_FIRST('0'), FIRST('1'); final Character code; StartFlag(Character code) { this.code = code; } public Character getCode() { return code; } } private StartFlag startFlag = StartFlag.FIRST; /* * Icon on Left of Title Bar * 00 : Internet Radio, 01 : Server, 02 : USB, 03 : iPod, 04 : DLNA, 05 : WiFi, 06 : Favorite * 10 : Account(Spotify), 11 : Album(Spotify), 12 : Playlist(Spotify), 13 : Playlist-C(Spotify) * 14 : Starred(Spotify), 15 : What's New(Spotify), 16 : Track(Spotify), 17 : Artist(Spotify) * 18 : Play(Spotify), 19 : Search(Spotify), 1A : Folder(Spotify) * FF : None */ private enum LeftIcon implements StringParameterIf { INTERNET_RADIO("00"), SERVER("01"), USB("02"), IPOD("03"), DLNA("04"), WIFI("05"), FAVORITE("06"), ACCOUNT_SPOTIFY("10"), ALBUM_SPOTIFY("11"), PLAYLIST_SPOTIFY("12"), PLAYLIST_C_SPOTIFY("13"), STARRED_SPOTIFY("14"), WHATS_NEW_SPOTIFY("15"), TRACK_SPOTIFY("16"), ARTIST_SPOTIFY("17"), PLAY_SPOTIFY("18"), SEARCH_SPOTIFY("19"), FOLDER_SPOTIFY("1A"), NONE("FF"); final String code; LeftIcon(String code) { this.code = code; } public String getCode() { return code; } } private LeftIcon leftIcon = LeftIcon.NONE; private ServiceType rightIcon = ServiceType.UNKNOWN; /* * ss : Status Info * 00 : None, 01 : Connecting, 02 : Acquiring License, 03 : Buffering * 04 : Cannot Play, 05 : Searching, 06 : Profile update, 07 : Operation disabled * 08 : Server Start-up, 09 : Song rated as Favorite, 0A : Song banned from station, * 0B : Authentication Failed, 0C : Spotify Paused(max 1 device), 0D : Track Not Available, 0E : Cannot Skip */ private enum StatusInfo implements StringParameterIf { NONE("00"), CONNECTING("01"), ACQUIRING_LICENSE("02"), BUFFERING("03"), CANNOT_PLAY("04"), SEARCHING("05"), PROFILE_UPDATE("06"), OPERATION_DISABLED("07"), SERVER_START_UP("08"), SONG_RATED_AS_FAVORITE("09"), SONG_BANNED_FROM_STATION("0A"), AUTHENTICATION_FAILED("0B"), SPOTIFY_PAUSED("0C"), TRACK_NOT_AVAILABLE("0D"), CANNOT_SKIP("0E"); final String code; StatusInfo(String code) { this.code = code; } public String getCode() { return code; } } private StatusInfo statusInfo = StatusInfo.NONE; /* Character of Title Bar (variable-length, 64 Unicode letters [UTF-8 encoded] max) */ private String titleBar; ListTitleInfoMsg(EISCPMessage raw) throws Exception { super(raw); /* NET/USB List Title Info xx : Service Type u : UI Type y : Layer Info cccc : Current Cursor Position (HEX 4 letters) iiii : Number of List Items (HEX 4 letters) ll : Number of Layer(HEX 2 letters) s : Start Flag r : Reserved (1 leters, don't care) aa : Icon on Left of Title Bar bb : Icon on Right of Title Bar ss : Status Info nnn...nnn : Character of Title Bar (variable-length, 64 Unicode letters [UTF-8 encoded] max) */ final String format = "xxuycccciiiillsraabbss"; if (data.length() >= format.length()) { serviceType = (ServiceType) searchParameter(data.substring(0, 2), ServiceType.values(), serviceType); uiType = (UIType) searchParameter(data.charAt(2), UIType.values(), uiType); layerInfo = (LayerInfo) searchParameter(data.charAt(3), LayerInfo.values(), layerInfo); currentCursorPosition = Integer.parseInt(data.substring(4, 8), 16); numberOfItems = Integer.parseInt(data.substring(8, 12), 16); numberOfLayers = Integer.parseInt(data.substring(12, 14), 16); startFlag = (StartFlag) searchParameter(data.charAt(14), StartFlag.values(), startFlag); leftIcon = (LeftIcon) searchParameter(data.substring(16, 18), LeftIcon.values(), leftIcon); rightIcon = (ServiceType) searchParameter(data.substring(18, 20), ServiceType.values(), rightIcon); statusInfo = (StatusInfo) searchParameter(data.substring(20, 22), StatusInfo.values(), statusInfo); titleBar = data.substring(22); } } public ServiceType getServiceType() { return serviceType; } public UIType getUiType() { return uiType; } public LayerInfo getLayerInfo() { return layerInfo; } public int getNumberOfItems() { return numberOfItems; } public int getCurrentCursorPosition() { return currentCursorPosition; } public int getNumberOfLayers() { return numberOfLayers; } public String getTitleBar() { return titleBar; } @NonNull @Override public String toString() { return CODE + "[" + data + "; SERVICE=" + serviceType.toString() + "; UI=" + uiType.toString() + "; LAYER=" + layerInfo + "; CURSOR=" + currentCursorPosition + "; ITEMS=" + numberOfItems + "; LAYERS=" + numberOfLayers + "; START=" + startFlag.toString() + "; LEFT_ICON=" + leftIcon.toString() + "; RIGHT_ICON=" + rightIcon.toString() + "; STATUS=" + statusInfo.toString() + "; title=" + titleBar + "]"; } public boolean isNetTopService() { return serviceType == ServiceType.NET && layerInfo == ListTitleInfoMsg.LayerInfo.NET_TOP; } public boolean isXmlListTopService() { return (serviceType == ServiceType.USB_FRONT || serviceType == ServiceType.USB_REAR || serviceType == ServiceType.MUSIC_SERVER || serviceType == ServiceType.HOME_MEDIA ) && layerInfo == LayerInfo.SERVICE_TOP; } }
8,719
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
MultiroomDeviceInformationMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/MultiroomDeviceInformationMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import com.mkulesh.onpc.utils.Logging; import com.mkulesh.onpc.utils.Utils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /* * Multiroom Device Information Command: gets the Multiroom Device Information as an XML message: * <mdi> * <deviceid>111111111111</deviceid> * <currentversion>100</currentversion> * <zonelist> *  <zone id="1" groupid="3" ch="ST" role="src" roomname="" groupname="" powerstate="1" iconid="1" color="1" delay="1000"/> * <zone id="2" groupid="3" ch="ST" role="dst" roomname="" groupname="" powerstate="1" iconid="1" color="1" delay="1000"/> * <zone id="3" groupid="1" ch="ST" role="none" roomname="" groupname="" powerstate="1" iconid="1" color="1" delay="1000"/> * </zonelist> * </mdi> */ public class MultiroomDeviceInformationMsg extends ISCPMessage { public final static String CODE = "MDI"; public final static int NO_GROUP = 0; public enum ChannelType { ST, FL, FR, NONE } @SuppressWarnings("unused") public enum RoleType implements StringParameterIf { SRC("SRC", R.string.multiroom_master), DST("DST", R.string.multiroom_slave), NONE("NONE", R.string.multiroom_none); final String code; @StringRes final int descriptionId; RoleType(final String code, @StringRes final int descriptionId) { this.code = code; this.descriptionId = descriptionId; } public String getCode() { return code; } @StringRes public int getDescriptionId() { return descriptionId; } } public static class Zone { final int id; final int groupid; final ChannelType ch; final RoleType role; final String roomname; final String groupname; final int powerstate; final int iconid; final int color; final int delay; Zone(Element e) { id = Integer.parseInt(e.getAttribute("id")); groupid = e.hasAttribute("groupid") ? Integer.parseInt(e.getAttribute("groupid")) : NO_GROUP; ch = e.hasAttribute("ch") ? ChannelType.valueOf(e.getAttribute("ch").toUpperCase()) : ChannelType.NONE; role = e.hasAttribute("role") ? RoleType.valueOf(e.getAttribute("role").toUpperCase()) : RoleType.NONE; roomname = e.hasAttribute("roomname") ? e.getAttribute("roomname") : ""; groupname = e.hasAttribute("groupname") ? e.getAttribute("groupname") : ""; powerstate = e.hasAttribute("powerstate") ? Integer.parseInt(e.getAttribute("powerstate")) : -1; iconid = e.hasAttribute("iconid") ? Integer.parseInt(e.getAttribute("iconid")) : -1; color = e.hasAttribute("color") ? Integer.parseInt(e.getAttribute("color")) : -1; delay = e.hasAttribute("delay") ? Integer.parseInt(e.getAttribute("delay")) : -1; } @NonNull @Override public String toString() { return id + ": groupid=" + groupid + ", ch=" + ch.toString() + ", role=" + role.toString() + ", roomname=" + roomname + ", groupname=" + groupname + ", powerstate=" + powerstate + ", iconid=" + iconid + ", color=" + color + ", delay=" + delay; } int getId() { return id; } public int getGroupid() { return groupid; } } private final HashMap<String, String> properties = new HashMap<>(); private final List<MultiroomDeviceInformationMsg.Zone> zones = new ArrayList<>(); MultiroomDeviceInformationMsg(EISCPMessage raw) throws Exception { super(raw); } @NonNull @Override public String toString() { return CODE + "[" + (isMultiline() ? ("XML<" + data.length() + "B>") : ("XML=" + data)) + "]"; } public void parseXml(boolean showInfo) throws Exception { properties.clear(); zones.clear(); InputStream stream = new ByteArrayInputStream(data.getBytes(Utils.UTF_8)); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.parse(stream); final Element mdi = Utils.getElement(doc, "mdi"); if (mdi == null) { throw new Exception("mdi element not found"); } for (Node prop = mdi.getFirstChild(); prop != null; prop = prop.getNextSibling()) { if (prop instanceof Element) { final Element en = (Element) prop; if ("zonelist".equals(en.getTagName())) { final List<Element> elZone = Utils.getElements(en, "zone"); for (Element element : elZone) { final String id = element.getAttribute("id"); if (id != null) { zones.add(new MultiroomDeviceInformationMsg.Zone(element)); } } } else if (en.getChildNodes().getLength() == 1) { properties.put(en.getTagName(), en.getChildNodes().item(0).getNodeValue()); } } } if (showInfo) { for (Map.Entry<String, String> p : properties.entrySet()) { Logging.info(this, " Property: " + p.getKey() + "=" + p.getValue()); } for (MultiroomDeviceInformationMsg.Zone s : zones) { Logging.info(this, " Zone " + s.toString()); } } } @NonNull public String getProperty(final String name) { String prop = properties.get(name); return prop == null ? "" : prop; } @NonNull public List<Zone> getZones() { return zones; } @NonNull public RoleType getRole(int zone) { for (MultiroomDeviceInformationMsg.Zone z : zones) { if (z.getId() == zone) { return z.role; } } return RoleType.NONE; } @NonNull public ChannelType getChannelType(int zone) { for (MultiroomDeviceInformationMsg.Zone z : zones) { if (z.getId() == zone) { return z.ch; } } return ChannelType.NONE; } public int getGroupId(int zone) { for (MultiroomDeviceInformationMsg.Zone z : zones) { if (z.getId() == zone) { return z.groupid; } } return NO_GROUP; } }
8,217
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
DcpAudioRestorerMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/DcpAudioRestorerMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import java.util.ArrayList; import java.util.Collections; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; /* * Denon control protocol - DCP audio restorer */ public class DcpAudioRestorerMsg extends ISCPMessage { public final static String CODE = "D04"; private final static String DCP_COMMAND = "PSRSTR"; @NonNull public static ArrayList<String> getAcceptedDcpCodes() { return new ArrayList<>(Collections.singletonList(DCP_COMMAND)); } public enum Status implements DcpStringParameterIf { NONE("N/A", R.string.device_dcp_audio_restorer_none), OFF("OFF", R.string.device_dcp_audio_restorer_off), LOW("LOW", R.string.device_dcp_audio_restorer_low), MED("MED", R.string.device_dcp_audio_restorer_medium), HI("HI", R.string.device_dcp_audio_restorer_high); final String code; @StringRes final int descriptionId; Status(final String code, @StringRes final int descriptionId) { this.code = code; this.descriptionId = descriptionId; } public String getCode() { return code; } @NonNull public String getDcpCode() { return code; } @StringRes public int getDescriptionId() { return descriptionId; } } private final Status status; DcpAudioRestorerMsg(EISCPMessage raw) throws Exception { super(raw); status = (Status) searchParameter(data, Status.values(), Status.NONE); } public DcpAudioRestorerMsg(Status status) { super(0, null); this.status = status; } public Status getStatus() { return status; } @NonNull @Override public String toString() { return CODE + "[" + status.toString() + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, status.getCode()); } @Override public boolean hasImpactOnMediaList() { return false; } @Nullable public static DcpAudioRestorerMsg processDcpMessage(@NonNull String dcpMsg) { final Status s = (Status) searchDcpParameter(DCP_COMMAND, dcpMsg, Status.values()); return s != null ? new DcpAudioRestorerMsg(s) : null; } @Nullable @Override public String buildDcpMsg(boolean isQuery) { // A space is needed for this command return DCP_COMMAND + " " + (isQuery ? DCP_MSG_REQ : status.getDcpCode()); } public static Status toggle(Status s) { switch (s) { case OFF: return Status.LOW; case LOW: return Status.MED; case MED: return Status.HI; case HI: return Status.OFF; default: return Status.NONE; } } }
3,807
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
XmlListItemMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/XmlListItemMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import com.mkulesh.onpc.utils.Utils; import org.w3c.dom.Element; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; public class XmlListItemMsg extends ISCPMessage { public enum Icon implements StringParameterIf { UNKNOWN("--", R.drawable.media_item_unknown), USB("31", R.drawable.media_item_usb), FOLDER("29", R.drawable.media_item_folder), MUSIC("2d", R.drawable.media_item_music), SEARCH("2F", R.drawable.media_item_search), PLAY("36", R.drawable.media_item_play), FOLDER_PLAY("HS01", R.drawable.media_item_folder_play), HEOS_SERVER("HS02", R.drawable.media_item_media_server); final String code; @DrawableRes final int imageId; Icon(String code, @DrawableRes int imageId) { this.code = code; this.imageId = imageId; } public String getCode() { return code; } @DrawableRes public int getImageId() { return imageId; } public boolean isSong() { return this == PLAY || this == MUSIC; } } private final int numberOfLayers; private final String title; private String iconType; private final String iconId; private Icon icon; private final boolean selectable; private ISCPMessage cmdMessage; XmlListItemMsg(final int id, final int numberOfLayers, final Element src) { super(id, null); this.numberOfLayers = numberOfLayers; title = src.getAttribute("title") == null ? "" : src.getAttribute("title"); iconType = src.getAttribute("icontype") == null ? "" : src.getAttribute("icontype"); iconId = src.getAttribute("iconid") == null ? Icon.UNKNOWN.getCode() : src.getAttribute("iconid"); icon = (Icon) searchParameter(iconId, Icon.values(), Icon.UNKNOWN); selectable = Utils.ensureAttribute(src, "selectable", "1"); cmdMessage = null; } public XmlListItemMsg(final int id, final int numberOfLayers, final String title, final Icon icon, final boolean selectable, final ISCPMessage cmdMessage) { super(id, null); this.numberOfLayers = numberOfLayers; this.title = title; iconType = ""; iconId = icon.getCode(); this.icon = icon; this.selectable = selectable; this.cmdMessage = cmdMessage; } private int getNumberOfLayers() { return numberOfLayers; } public Icon getIcon() { return icon; } public void setIcon(Icon icon) { this.icon = icon; } public String getTitle() { return title; } public void setIconType(String iconType) { this.iconType = iconType; } public String getIconType() { return iconType; } @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean isSelectable() { return selectable; } @NonNull @Override public String toString() { return "ITEM[" + messageId + ": " + title + "; ICON_TYPE=" + iconType + "; ICON_ID=" + iconId + "; ICON=" + icon.toString() + "; SELECTABLE=" + selectable + "; CMD=" + cmdMessage + "]"; } public void setCmdMessage(ISCPMessage cmdMessage) { this.cmdMessage = cmdMessage; } @Override public EISCPMessage getCmdMsg() { if (cmdMessage != null) { return cmdMessage.getCmdMsg(); } else { final String param = "I" + String.format("%02x", getNumberOfLayers()) + String.format("%04x", getMessageId()) + "----"; return new EISCPMessage("NLA", param); } } public ISCPMessage getCmdMessage() { return cmdMessage; } }
4,821
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
SubwooferLevelCommandMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/SubwooferLevelCommandMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import com.mkulesh.onpc.utils.Utils; import androidx.annotation.NonNull; /* * Subwoofer (temporary) Level Command */ public class SubwooferLevelCommandMsg extends ISCPMessage { public final static String CODE = "SWL"; public final static String KEY = "Subwoofer Level"; public final static int NO_LEVEL = 0xFF; private int level, cmdLength; SubwooferLevelCommandMsg(EISCPMessage raw) throws Exception { super(raw); try { level = Integer.parseInt(data, 16); cmdLength = data.length(); } catch (Exception e) { level = NO_LEVEL; cmdLength = NO_LEVEL; } } public SubwooferLevelCommandMsg(int level, int cmdLength) { super(0, null); this.level = level; this.cmdLength = cmdLength; } public int getLevel() { return level; } public int getCmdLength() { return cmdLength; } @NonNull @Override public String toString() { return CODE + "[" + data + "; LEVEL=" + level + "; CMD_LENGTH=" + cmdLength + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, Utils.intLevelToString(level, cmdLength)); } @Override public boolean hasImpactOnMediaList() { return false; } }
2,179
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
DcpReceiverInformationMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/DcpReceiverInformationMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.jayway.jsonpath.JsonPath; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import com.mkulesh.onpc.utils.Logging; import com.mkulesh.onpc.utils.Utils; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /* * Denon control protocol - maximum volume and input selectors */ public class DcpReceiverInformationMsg extends ISCPMessage { public final static String CODE = "D01"; // Input selectors public final static String DCP_COMMAND_INPUT_SEL = "SSFUN"; private final static String DCP_COMMAND_END = "END"; // Max. Volume public final static String DCP_COMMAND_MAXVOL = "MVMAX"; public final static String DCP_COMMAND_ALIMIT = "SSVCTZMALIM"; // Tone control public final static String[] DCP_COMMANDS_BASS = new String[]{ "PSBAS", "Z2PSBAS", "Z3PSBAS" }; public final static String[] DCP_COMMANDS_TREBLE = new String[]{ "PSTRE", "Z2PSTRE", "Z3PSTRE" }; public final static int[] DCP_TON_MAX = new int[]{ 6, 10, 10 }; public final static int[] DCP_TON_SHIFT = new int[]{ 50, 50, 50 }; // Radio presets public final static String DCP_COMMAND_PRESET = "OPTPN"; // Firmware public final static String DCP_COMMAND_FIRMWARE_VER = "SSINFFRM"; // Get Music Sources Command: heos://browse/get_music_sources private final static String HEOS_COMMAND_NET = "browse/get_music_sources"; @NonNull public static ArrayList<String> getAcceptedDcpCodes() { final ArrayList<String> out = new ArrayList<>(Arrays.asList( DCP_COMMAND_INPUT_SEL, DCP_COMMAND_MAXVOL, DCP_COMMAND_ALIMIT, DCP_COMMAND_PRESET, DCP_COMMAND_FIRMWARE_VER)); out.addAll(Arrays.asList(DCP_COMMANDS_BASS)); out.addAll(Arrays.asList(DCP_COMMANDS_TREBLE)); return out; } public enum UpdateType { NONE, SELECTOR, MAX_VOLUME, TONE_CONTROL, PRESET, NETWORK_SERVICES, FIRMWARE_VER } public final UpdateType updateType; private ReceiverInformationMsg.Selector selector = null; private ReceiverInformationMsg.Zone maxVolumeZone = null; private ReceiverInformationMsg.ToneControl toneControl = null; private ReceiverInformationMsg.Preset preset = null; private Map<String, ReceiverInformationMsg.NetworkService> networkServices = new HashMap<>(); private String firmwareVer = null; // Query interface public enum QueryType implements StringParameterIf { NONE, FULL, SHORT; @Override public String getCode() { return name(); } } private QueryType queryType = QueryType.NONE; public DcpReceiverInformationMsg(QueryType q) { super(-1, ""); this.updateType = UpdateType.NONE; this.queryType = q; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, queryType.getCode()); } // Data message interface DcpReceiverInformationMsg(EISCPMessage raw) throws Exception { super(raw); this.updateType = UpdateType.NONE; this.queryType = (QueryType) searchParameter(data, QueryType.values(), QueryType.NONE); } public DcpReceiverInformationMsg(@NonNull final ReceiverInformationMsg.Selector selector) { super(-1, ""); this.updateType = UpdateType.SELECTOR; this.selector = selector; } public DcpReceiverInformationMsg(@NonNull final ReceiverInformationMsg.Zone zone) { super(-1, ""); this.updateType = UpdateType.MAX_VOLUME; maxVolumeZone = zone; } public DcpReceiverInformationMsg(@NonNull final ReceiverInformationMsg.ToneControl toneControl) { super(-1, ""); this.updateType = UpdateType.TONE_CONTROL; this.toneControl = toneControl; } public DcpReceiverInformationMsg(@NonNull final ReceiverInformationMsg.Preset preset) { super(-1, ""); this.updateType = UpdateType.PRESET; this.preset = preset; } public DcpReceiverInformationMsg(final Map<String, ReceiverInformationMsg.NetworkService> networkServices) { super(-1, ""); this.updateType = UpdateType.NETWORK_SERVICES; this.networkServices = networkServices; } public DcpReceiverInformationMsg(final UpdateType type, final String par) { super(-1, ""); this.updateType = type; this.firmwareVer = par; } public ReceiverInformationMsg.Selector getSelector() { return selector; } public ReceiverInformationMsg.Zone getMaxVolumeZone() { return maxVolumeZone; } public ReceiverInformationMsg.ToneControl getToneControl() { return toneControl; } public ReceiverInformationMsg.Preset getPreset() { return preset; } public Map<String, ReceiverInformationMsg.NetworkService> getNetworkServices() { return networkServices; } public String getFirmwareVer() { return firmwareVer; } @NonNull @Override public String toString() { return "DCP receiver configuration: " + (updateType != UpdateType.NONE ? "UpdateType=" + updateType + " " : "") + (queryType != QueryType.NONE ? "Query=" + queryType + " " : "") + (selector != null ? "Selector=" + selector + " " : "") + (maxVolumeZone != null ? "MaxVol=" + maxVolumeZone.volMax + " " : "") + (toneControl != null ? "ToneCtrl=" + toneControl + " " : "") + (preset != null ? "Preset=" + preset + " " : "") + (!networkServices.isEmpty() ? "NetworkServices=" + networkServices.size() + " " : "") + (firmwareVer != null ? "Firmware=" + firmwareVer + " " : ""); } @Nullable public static DcpReceiverInformationMsg processDcpMessage(@NonNull String dcpMsg) { // Input Selector if (dcpMsg.startsWith(DCP_COMMAND_INPUT_SEL)) { final String par = dcpMsg.substring(DCP_COMMAND_INPUT_SEL.length()).trim(); if (DCP_COMMAND_END.equalsIgnoreCase(par)) { return null; } final int sepIdx = par.indexOf(' '); if (sepIdx < 0) { Logging.info(DcpReceiverInformationMsg.class, "DCP selector " + par + ": separator not found"); } final String code = par.substring(0, sepIdx).trim(); final String name = par.substring(sepIdx).trim(); final InputSelectorMsg.InputType item = (InputSelectorMsg.InputType) InputSelectorMsg.searchParameter( code, InputSelectorMsg.InputType.values(), InputSelectorMsg.InputType.NONE); if (item == InputSelectorMsg.InputType.NONE) { Logging.info(DcpReceiverInformationMsg.class, "DCP input selector not known: " + par); return null; } return new DcpReceiverInformationMsg( new ReceiverInformationMsg.Selector( item.getCode(), name, ReceiverInformationMsg.ALL_ZONES, "", false)); } // Max Volume if (dcpMsg.startsWith(DCP_COMMAND_MAXVOL)) { return processMaxVolume(dcpMsg.substring(DCP_COMMAND_MAXVOL.length()).trim(), true); } if (dcpMsg.startsWith(DCP_COMMAND_ALIMIT)) { return processMaxVolume(dcpMsg.substring(DCP_COMMAND_ALIMIT.length()).trim(), false); } // Bass for (int i = 0; i < DCP_COMMANDS_BASS.length; i++) { if (dcpMsg.startsWith(DCP_COMMANDS_BASS[i])) { return new DcpReceiverInformationMsg( new ReceiverInformationMsg.ToneControl( ToneCommandMsg.BASS_KEY, -DCP_TON_MAX[i], DCP_TON_MAX[i], 1)); } } // Treble for (int i = 0; i < DCP_COMMANDS_TREBLE.length; i++) { if (dcpMsg.startsWith(DCP_COMMANDS_TREBLE[i])) { return new DcpReceiverInformationMsg( new ReceiverInformationMsg.ToneControl( ToneCommandMsg.TREBLE_KEY, -DCP_TON_MAX[i], DCP_TON_MAX[i], 1)); } } // Radio Preset if (dcpMsg.startsWith(DCP_COMMAND_PRESET)) { final String par = dcpMsg.substring(DCP_COMMAND_PRESET.length()).trim(); if (par.length() > 2) { try { final int num = Integer.parseInt(par.substring(0, 2)); final String name = par.substring(2).trim(); if (Utils.isInteger(name)) { final float f = (float) Integer.parseInt(name) / 100.0f; final DecimalFormat df = Utils.getDecimalFormat("0.00"); return new DcpReceiverInformationMsg( new ReceiverInformationMsg.Preset( num, /*band FM*/ 1, df.format(f), "")); } else { return new DcpReceiverInformationMsg( new ReceiverInformationMsg.Preset( num, /*band DAB*/ 2, "0", name)); } } catch (Exception nfe) { // nothing to do } } Logging.info(DcpReceiverInformationMsg.class, "DCP preset invalid: " + par); } // Firmware version if (dcpMsg.startsWith(DCP_COMMAND_FIRMWARE_VER)) { final String par = dcpMsg.substring(DCP_COMMAND_FIRMWARE_VER.length()).trim(); if (!DCP_COMMAND_END.equalsIgnoreCase(par)) { return new DcpReceiverInformationMsg(UpdateType.FIRMWARE_VER, par); } } return null; } static DcpReceiverInformationMsg processMaxVolume(final String par, boolean scale) { try { int maxVolume = Integer.parseInt(par); if (scale && par.length() > 2) { maxVolume = maxVolume / 10; } // Create a zone with max volume received in the message return new DcpReceiverInformationMsg(new ReceiverInformationMsg.Zone( "", "", 0, maxVolume)); } catch (Exception e) { Logging.info(DcpReceiverInformationMsg.class, "Unable to parse max. volume level " + par); return null; } } @Nullable public static DcpReceiverInformationMsg processHeosMessage(@NonNull final String command, @NonNull final String heosMsg) { if (HEOS_COMMAND_NET.equals(command)) { final List<String> names = JsonPath.read(heosMsg, "$.payload[*].name"); final List<Integer> sids = JsonPath.read(heosMsg, "$.payload[*].sid"); if (names.size() != sids.size()) { Logging.info(DcpReceiverInformationMsg.class, "Inconsistent size of manes and sids"); return null; } final Map<String, ReceiverInformationMsg.NetworkService> networkServices = new HashMap<>(); for (int i = 0; i < names.size(); i++) { final String id = "HS" + sids.get(i); final ServiceType s = (ServiceType) searchParameter(id, ServiceType.values(), null); if (s == null) { Logging.info(DcpReceiverInformationMsg.class, "Service " + names.get(i) + " is not supported"); continue; } networkServices.put(id, new ReceiverInformationMsg.NetworkService( id, names.get(i), ReceiverInformationMsg.ALL_ZONES, false, false)); } if (!networkServices.isEmpty()) { ensureNetworkService(networkServices, ServiceType.DCP_PLAYQUEUE); ensureNetworkService(networkServices, ServiceType.DCP_SPOTIFY); return new DcpReceiverInformationMsg(networkServices); } } return null; } private static void ensureNetworkService(final Map<String, ReceiverInformationMsg.NetworkService> nsList, final ServiceType s) { final boolean missing = nsList.get(s.getCode()) == null; if (missing) { Logging.info(s, "Enforced missing network service " + s); nsList.put(s.getCode(), new ReceiverInformationMsg.NetworkService( s.getCode(), s.getName(), ReceiverInformationMsg.ALL_ZONES, false, false)); } } @Nullable @Override public String buildDcpMsg(boolean isQuery) { final StringBuilder res = new StringBuilder(); res.append("heos://system/register_for_change_events?enable=on"); res.append(DCP_MSG_SEP + "heos://" + HEOS_COMMAND_NET); res.append(DCP_MSG_SEP + DCP_COMMAND_INPUT_SEL + " ?"); res.append(DCP_MSG_SEP + DCP_COMMAND_FIRMWARE_VER + " ?"); if (queryType == QueryType.FULL) { res.append(DCP_MSG_SEP + DCP_COMMAND_PRESET + " ?"); } return res.toString(); } }
14,497
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
AudioMutingMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/AudioMutingMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.ConnectionIf; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ZonedMessage; import java.util.ArrayList; import java.util.Arrays; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; /* * Audio Muting Command */ public class AudioMutingMsg extends ZonedMessage { final static String CODE = "AMT"; final static String ZONE2_CODE = "ZMT"; final static String ZONE3_CODE = "MT3"; final static String ZONE4_CODE = "MT4"; public final static String[] ZONE_COMMANDS = new String[]{ CODE, ZONE2_CODE, ZONE3_CODE, ZONE4_CODE }; public enum Status implements DcpStringParameterIf { NONE("N/A", "N/A", R.string.audio_muting_none), OFF("00", "OFF", R.string.audio_muting_off), ON("01", "ON", R.string.audio_muting_on), TOGGLE("TG", "N/A", R.string.audio_muting_toggle); final String code, dcpCode; @StringRes final int descriptionId; Status(String code, String dcpCode, @StringRes final int descriptionId) { this.code = code; this.dcpCode = dcpCode; this.descriptionId = descriptionId; } public String getCode() { return code; } @NonNull public String getDcpCode() { return dcpCode; } @StringRes public int getDescriptionId() { return descriptionId; } } private final Status status; AudioMutingMsg(EISCPMessage raw) throws Exception { super(raw, ZONE_COMMANDS); status = (Status) searchParameter(data, Status.values(), Status.NONE); } public AudioMutingMsg(int zoneIndex, Status level) { super(0, null, zoneIndex); this.status = level; } @Override public String getZoneCommand() { return ZONE_COMMANDS[zoneIndex]; } public Status getStatus() { return status; } @NonNull @Override public String toString() { return getZoneCommand() + "[" + data + "; ZONE_INDEX=" + zoneIndex + "; STATUS=" + status.toString() + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(getZoneCommand(), status.getCode()); } @Override public boolean hasImpactOnMediaList() { return false; } public static Status toggle(Status s, ProtoType proto) { return proto == ConnectionIf.ProtoType.ISCP ? Status.TOGGLE : ((s == Status.OFF) ? Status.ON : Status.OFF); } /* * Denon control protocol */ private final static String[] DCP_COMMANDS = new String[]{ "MU", "Z2MU", "Z3MU" }; @NonNull public static ArrayList<String> getAcceptedDcpCodes() { return new ArrayList<>(Arrays.asList(DCP_COMMANDS)); } @Nullable public static AudioMutingMsg processDcpMessage(@NonNull String dcpMsg) { for (int i = 0; i < DCP_COMMANDS.length; i++) { final Status s = (Status) searchDcpParameter(DCP_COMMANDS[i], dcpMsg, Status.values()); if (s != null) { return new AudioMutingMsg(i, s); } } return null; } @Nullable @Override public String buildDcpMsg(boolean isQuery) { if (zoneIndex < DCP_COMMANDS.length) { return DCP_COMMANDS[zoneIndex] + (isQuery ? DCP_MSG_REQ : status.getDcpCode()); } return null; } }
4,386
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
ReceiverInformationMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/ReceiverInformationMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.ConnectionIf; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import com.mkulesh.onpc.utils.Logging; import com.mkulesh.onpc.utils.Utils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.net.URL; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /* * Gets the Receiver Information Status */ public class ReceiverInformationMsg extends ISCPMessage { public final static String CODE = "NRI"; public final static int DEFAULT_ACTIVE_ZONE = 0; public final static int ALL_ZONES = 0xFF; public final static int EXT_ZONES = 14; // 1110 - all zones except main public static class NetworkService { final String id; final String name; final int zone; final boolean addToQueue; final boolean sort; NetworkService(Element e) { id = e.getAttribute("id").toUpperCase(); name = e.getAttribute("name"); zone = e.hasAttribute("zone") ? Integer.parseInt(e.getAttribute("zone")) : 1; addToQueue = e.hasAttribute("addqueue") && (Integer.parseInt(e.getAttribute("addqueue")) == 1); sort = e.hasAttribute("sort") && (Integer.parseInt(e.getAttribute("sort")) == 1); } public NetworkService(final String id, final String name, final int zone, final boolean addToQueue, final boolean sort) { this.id = id; this.name = name; this.zone = zone; this.addToQueue = addToQueue; this.sort = sort; } String getId() { return id; } @SuppressWarnings("unused") public String getName() { return name; } public boolean isAddToQueue() { return addToQueue; } public boolean isSort() { return sort; } @NonNull @Override public String toString() { StringBuilder res = new StringBuilder(); res.append(id) .append(": ").append(name) .append(", addToQueue=").append(addToQueue) .append(", sort=").append(sort) .append(", zone=").append(zone) .append(", zones=["); for (int z = 0; z <= 3; z++) { res.append(Integer.valueOf((isActiveForZone(z) ? 1 : 0)).toString()); } res.append("]"); return res.toString(); } boolean isActiveForZone(int z) { return ((1 << z) & zone) != 0; } } public static class Zone { final String id; final String name; final int volumeStep; int volMax; Zone(Element e) { id = e.getAttribute("id").toUpperCase(); name = e.getAttribute("name"); volumeStep = e.hasAttribute("volstep") ? Integer.parseInt(e.getAttribute("volstep")) : 0; volMax = e.hasAttribute("volmax") ? Integer.parseInt(e.getAttribute("volmax")) : 0; } @SuppressWarnings("SameParameterValue") Zone(final String id, final String name, final int volumeStep, final int volMax) { this.id = id; this.name = name; this.volumeStep = volumeStep; this.volMax = volMax; } public String getName() { return name; } /* * Step = 0: scaled by 2 * Step = 1: use not scaled */ public int getVolumeStep() { return volumeStep; } public int getVolMax() { return volMax; } public void setVolMax(int volMax) { this.volMax = volMax; } @NonNull @Override public String toString() { return id + ": " + name + ", volumeStep=" + volumeStep + ", volMax=" + volMax; } @SuppressWarnings("unused") public boolean equals(Zone other) { return other != null && id.equals(other.id) && name.equals(other.name) && volumeStep == other.volumeStep && volMax == other.volMax; } } public static class Selector { final String id; final String name; final int zone; final String iconId; final boolean addToQueue; Selector(Element e) { id = e.getAttribute("id").toUpperCase(); name = e.getAttribute("name"); zone = e.hasAttribute("zone") ? Integer.parseInt(e.getAttribute("zone")) : 1; iconId = e.getAttribute("iconid"); addToQueue = e.hasAttribute("addqueue") && (Integer.parseInt(e.getAttribute("addqueue")) == 1); } public Selector(final String id, final String name, final int zone, final String iconId, final boolean addToQueue) { this.id = id; this.name = name; this.zone = zone; this.iconId = iconId; this.addToQueue = addToQueue; } public Selector(final Selector old, final String name) { this.id = old.id; this.name = name; this.zone = old.zone; this.iconId = old.iconId; this.addToQueue = old.addToQueue; } public Selector(final Selector old, final int zone) { this.id = old.id; this.name = old.name; this.zone = zone; this.iconId = old.iconId; this.addToQueue = old.addToQueue; } public String getId() { return id; } public String getName() { return name; } public boolean isAddToQueue() { return addToQueue; } @NonNull @Override public String toString() { StringBuilder res = new StringBuilder(); res.append(id) .append(": ").append(name) .append(", icon=").append(iconId) .append(", addToQueue=").append(addToQueue) .append(", zone=").append(zone) .append(", zones=["); for (int z = 0; z <= 3; z++) { res.append(Integer.valueOf((isActiveForZone(z) ? 1 : 0)).toString()); } res.append("]"); return res.toString(); } public boolean isActiveForZone(int z) { return ((1 << z) & zone) != 0; } } public static class Preset { final int id; final int band; final String freq; final String name; Preset(Element e, ProtoType protoType) { if (protoType == ConnectionIf.ProtoType.ISCP) { // <preset id="08" band="1" freq="97.30" name="" /> id = Integer.parseInt(e.getAttribute("id"), 16); band = Integer.parseInt(e.getAttribute("band")); freq = e.getAttribute("freq"); name = e.getAttribute("name").trim(); } else { // <value index="1" skip="OFF" table="01" band="FM" param=" 008830"/> final DecimalFormat df = Utils.getDecimalFormat("0.00"); final String par = e.getAttribute("param").trim(); final boolean freqValid = Utils.isInteger(par); id = Integer.parseInt(e.getAttribute("index")); band = "FM".equalsIgnoreCase(e.getAttribute("band")) ? 1 : 2; freq = band == 1 && freqValid ? df.format((float) Integer.parseInt(par) / 100.0f) : "0"; name = band == 1 ? "" : par; } } public Preset(final int id, final int band, final String freq, final String name) { this.id = id; this.band = band; this.freq = freq; this.name = name; } public int getId() { return id; } int getBand() { return band; } public String getName() { return name; } public boolean isEmpty() { return band == 0 && !isFreqValid() && name.isEmpty(); } boolean isFreqValid() { return freq != null && !freq.equals("0"); } public boolean isFm() { return getBand() == 1; } public boolean isAm() { return getBand() == 2 && isFreqValid(); } public boolean isDab() { return getBand() == 2 && !isFreqValid(); } @NonNull @Override public String toString() { return id + ": band=" + band + ", freq=" + freq + ", name=" + name; } @NonNull public String displayedString(boolean withId) { String res = name.trim(); final String band = (isFm() ? " MHz" : (isAm() ? " kHz" : " ")); if (!res.isEmpty() && isFreqValid()) { res += " - " + freq + band; } else if (res.isEmpty()) { res = freq + band; } return withId ? getId() + " - " + res : res; } @DrawableRes public int getImageId() { if (isAm()) { return R.drawable.media_item_radio_am; } else if (isFm()) { return R.drawable.media_item_radio_fm; } else if (isDab()) { return R.drawable.media_item_radio_dab; } return R.drawable.media_item_unknown; } @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean equals(Preset other) { return other != null && band == other.band && freq.equals(other.freq) && name.equals(other.name); } } public static class ToneControl { final String id; final int min, max, step; ToneControl(Element e) { id = e.getAttribute("id"); min = Integer.parseInt(e.getAttribute("min")); max = Integer.parseInt(e.getAttribute("max")); step = Integer.parseInt(e.getAttribute("step")); } public ToneControl(final String id, final int min, final int max, final int step) { this.id = id; this.min = min; this.max = max; this.step = step; } static boolean isControl(Element e) { return e.hasAttribute("min") && e.hasAttribute("max") && e.hasAttribute("step"); } public String getId() { return id; } public int getMin() { return min; } public int getMax() { return max; } public int getStep() { return step; } @NonNull @Override public String toString() { return getId() + ": min=" + getMin() + ", max=" + getMax() + ", step=" + getStep(); } public boolean equals(ToneControl other) { return other != null && id.equals(other.id) && min == other.min && max == other.max && step == other.step; } } private final ProtoType protoType; private final String dcpPresetData; private String deviceId = ""; private final HashMap<String, String> deviceProperties = new HashMap<>(); private final HashMap<String, NetworkService> networkServices = new HashMap<>(); private final List<Zone> zones = new ArrayList<>(); private final List<Selector> deviceSelectors = new ArrayList<>(); private final List<Preset> presetList = new ArrayList<>(); private final Set<String> controlList = new HashSet<>(); private final HashMap<String, ToneControl> toneControls = new HashMap<>(); public ReceiverInformationMsg(EISCPMessage raw) throws Exception { super(raw); protoType = ConnectionIf.ProtoType.ISCP; dcpPresetData = ""; } @NonNull public Map<String, String> getDeviceProperties() { return deviceProperties; } @NonNull public HashMap<String, NetworkService> getNetworkServices() { return networkServices; } public static List<Zone> getDefaultZones() { List<ReceiverInformationMsg.Zone> defaultZones = new ArrayList<>(); defaultZones.add(new Zone("1", "Main", 1, 0x82)); defaultZones.add(new Zone("2", "Zone2", 1, 0x82)); defaultZones.add(new Zone("3", "Zone3", 1, 0x82)); defaultZones.add(new Zone("4", "Zone4", 1, 0x82)); return defaultZones; } @NonNull public List<Zone> getZones() { return zones; } @NonNull public List<Selector> getDeviceSelectors() { return deviceSelectors; } @NonNull public List<Preset> getPresetList() { return presetList; } @NonNull public HashMap<String, ToneControl> getToneControls() { return toneControls; } @NonNull public Set<String> getControlList() { return controlList; } @NonNull @Override public String toString() { return CODE + "[" + (isMultiline() ? ("XML<" + data.length() + "B>") : ("XML=" + data)) + "]"; } public void parseXml(boolean showInfo) throws Exception { deviceProperties.clear(); networkServices.clear(); zones.clear(); deviceSelectors.clear(); presetList.clear(); controlList.clear(); toneControls.clear(); InputStream stream = new ByteArrayInputStream(data.getBytes(Utils.UTF_8)); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.parse(stream); if (protoType == ConnectionIf.ProtoType.ISCP) { parseIscpXml(doc); } else { parseDcpXml(doc); } if (showInfo) { Logging.info(this, " deviceId=" + deviceId); for (Map.Entry<String, String> p : deviceProperties.entrySet()) { Logging.info(this, " Property: " + p.getKey() + "=" + p.getValue()); } for (NetworkService s : networkServices.values()) { Logging.info(this, " Service " + s.toString()); } for (Zone s : zones) { Logging.info(this, " Zone " + s.toString()); } for (Selector s : deviceSelectors) { Logging.info(this, " Selector " + s.toString()); } for (Preset p : presetList) { Logging.info(this, " Preset " + p.toString()); } for (String s : controlList) { Logging.info(this, " Control: " + s); } for (ToneControl s : toneControls.values()) { Logging.info(this, " Tone control " + s.toString()); } } else { Logging.info(this, "receiver information parsed"); } stream.close(); } private void parseIscpXml(final Document doc) { for (Node object = doc.getDocumentElement(); object != null; object = object.getNextSibling()) { if (object instanceof Element) { final Element response = (Element) object; if (!response.getTagName().equals("response") || !Utils.ensureAttribute(response, "status", "ok")) { continue; } final List<Element> device = Utils.getElements(response, "device"); if (device.isEmpty()) { continue; } // Only process the first "items" element Element deviceInfo = device.get(0); if (deviceInfo == null) { continue; } deviceId = deviceInfo.getAttribute("id"); for (Node prop = deviceInfo.getFirstChild(); prop != null; prop = prop.getNextSibling()) { if (prop instanceof Element) { final Element en = (Element) prop; if (en.getChildNodes().getLength() == 1) { deviceProperties.put(en.getTagName(), en.getChildNodes().item(0).getNodeValue()); } else if ("netservicelist".equals(en.getTagName())) { final List<Element> elService = Utils.getElements(en, "netservice"); for (Element element : elService) { final String id = element.getAttribute("id"); final String value = element.getAttribute("value"); final String name = element.getAttribute("name"); if (id != null && value != null && Integer.parseInt(value) == 1 && name != null) { final NetworkService n = new NetworkService(element); networkServices.put(n.getId(), n); } } } else if ("zonelist".equals(en.getTagName())) { final List<Element> elZone = Utils.getElements(en, "zone"); for (Element element : elZone) { final String id = element.getAttribute("id"); final String value = element.getAttribute("value"); if (id != null && value != null && Integer.parseInt(value) == 1) { zones.add(new Zone(element)); } } } else if ("selectorlist".equals(en.getTagName())) { final List<Element> elSelectors = Utils.getElements(en, "selector"); for (Element element : elSelectors) { deviceSelectors.add(new Selector(element)); } } else if ("presetlist".equals(en.getTagName())) { final List<Element> elPresets = Utils.getElements(en, "preset"); for (Element element : elPresets) { final String id = element.getAttribute("id"); final String band = element.getAttribute("band"); final String name = element.getAttribute("name"); if (id != null && band != null && name != null) { presetList.add(new Preset(element, ConnectionIf.ProtoType.ISCP)); } } } else if ("controllist".equals(en.getTagName())) { final List<Element> elControls = Utils.getElements(en, "control"); for (Element element : elControls) { final String id = element.getAttribute("id"); final String value = element.getAttribute("value"); if (id != null && value != null && Integer.parseInt(value) == 1) { controlList.add(id); if (ToneControl.isControl(element)) { final ToneControl n = new ToneControl(element); toneControls.put(n.getId(), n); } } } } } } } } } /* * Denon control protocol */ public ReceiverInformationMsg(final String host, final int port) throws Exception { super(0, getDcpXmlData(host, port)); protoType = ConnectionIf.ProtoType.DCP; dcpPresetData = getDcpPresetData(host, port); if (data != null) { Logging.info(this, "DCP Receiver information from " + host + ":" + port + (dcpPresetData != null ? ", presets available" : ", presets not available")); } } private static String getDcpXmlData(final String host, final int port) throws Exception { final byte[] bytes = Utils.getUrlData(new URL(getDcpGoformUrl(host, port, "Deviceinfo.xml")), true); if (bytes != null) { final int offset = Utils.getUrlHeaderLength(bytes); final int length = bytes.length - offset; if (length > 0) { String s = new String(Utils.catBuffer(bytes, offset, length), Utils.UTF_8); s = s.replaceAll("\n", ""); return s; } } throw new Exception("DCP receiver information not available"); } private String getDcpPresetData(String host, int port) { try { final byte[] bytes = Utils.getUrlData(new URL(getDcpGoformUrl(host, port, "formiPhoneAppTunerPreset.xml")), true); if (bytes != null) { final int offset = Utils.getUrlHeaderLength(bytes); final int length = bytes.length - offset; if (length > 0) { String s = new String(Utils.catBuffer(bytes, offset, length), Utils.UTF_8); s = s.replaceAll("\n", ""); return s; } } } catch (Exception ex) { // Nothing to do } return null; } private void parseDcpXml(final Document doc) throws Exception { final Element deviceInfo = Utils.getElement(doc, "Device_Info"); if (deviceInfo == null) { throw new Exception("Device_Info section is not found"); } for (Element en : Utils.getElements(deviceInfo, null)) { if (en.getChildNodes().getLength() == 1) { parseDcpDeviceProperties(en); } else if ("DeviceZoneCapabilities".equalsIgnoreCase(en.getTagName())) { parseDcpZoneCapabilities(en); } else if ("DeviceCapabilities".equalsIgnoreCase(en.getTagName())) { parseDcpDeviceCapabilities(en); } } try { parseDcpPresets(dcpPresetData); } catch (Exception ex) { Logging.info(this, "Cannot parse DCP presets: " + ex.getLocalizedMessage()); } } private void parseDcpDeviceProperties(Element en) { final Map<String, String> propNameMap = new HashMap<>(); propNameMap.put("BrandCode", "brand"); propNameMap.put("CategoryName", "category"); propNameMap.put("ManualModelName", "friendlyname"); propNameMap.put("ModelName", "model"); propNameMap.put("MacAddress", "macaddress"); final String iscpPropName = propNameMap.get(en.getTagName()); if (iscpPropName != null) { String val = en.getChildNodes().item(0).getNodeValue(); if (val == null) { return; } if ("model".equalsIgnoreCase(iscpPropName)) { deviceId = val; } if ("brand".equalsIgnoreCase(iscpPropName)) { val = val.equals("0") ? "Denon" : "Marantz"; } deviceProperties.put(iscpPropName, val); } } private void parseDcpZoneCapabilities(Element zoneCapabilities) { final List<Element> zones = Utils.getElements(zoneCapabilities, "Zone"); final List<Element> volumes = Utils.getElements(zoneCapabilities, "Volume"); final List<Element> input = Utils.getElements(zoneCapabilities, "InputSource"); if (zones.size() != 1) { return; } if (zones.size() == volumes.size()) { String no = Utils.getFirstElementValue(zones.get(0), "No", null); String maxVolume = Utils.getFirstElementValue(volumes.get(0), "MaxValue", null); String step = Utils.getFirstElementValue(volumes.get(0), "StepValue", null); if (no != null && maxVolume != null && step != null) { final int noInt = Integer.parseInt(no) + 1; final String name = noInt == 1 ? "Main" : "Zone" + noInt; // Volume for zone 1 is ***:00 to 98 -> scale can be 0 // Volume for zone 2/3 is **:00 to 98 -> scale shall be 1 final int stepInt = noInt == 1 ? (int) Float.parseFloat(step) : 1; final int maxVolumeInt = (int) Float.parseFloat(maxVolume); this.zones.add(new Zone(String.valueOf(noInt), name, stepInt, maxVolumeInt)); } } if (zones.size() == input.size()) { String no = Utils.getFirstElementValue(zones.get(0), "No", null); final String ctrl = Utils.getFirstElementValue(input.get(0), "Control", "0"); final List<Element> list = Utils.getElements(input.get(0), "List"); if (no != null && ctrl != null && ctrl.equals("1") && list.size() == 1) { final List<Element> sources = Utils.getElements(list.get(0), "Source"); for (Element source : sources) { parceDcpInput(Integer.parseInt(no), Utils.getFirstElementValue(source, "FuncName", null), Utils.getFirstElementValue(source, "DefaultName", null), Utils.getFirstElementValue(source, "IconId", "")); } } } } private void parceDcpInput(int zone, @Nullable String name, @Nullable String defName, @Nullable String iconId) { if (name == null || iconId == null) { return; } final Map<String, InputSelectorMsg.InputType> funcNameMap = new HashMap<>(); funcNameMap.put("PHONO", InputSelectorMsg.InputType.DCP_PHONO); funcNameMap.put("CD", InputSelectorMsg.InputType.DCP_CD); funcNameMap.put("DVD", InputSelectorMsg.InputType.DCP_DVD); funcNameMap.put("BLU-RAY", InputSelectorMsg.InputType.DCP_BD); funcNameMap.put("TV AUDIO", InputSelectorMsg.InputType.DCP_TV); funcNameMap.put("CBL/SAT", InputSelectorMsg.InputType.DCP_SAT_CBL); funcNameMap.put("MEDIA PLAYER", InputSelectorMsg.InputType.DCP_MPLAY); funcNameMap.put("GAME", InputSelectorMsg.InputType.DCP_GAME); funcNameMap.put("TUNER", InputSelectorMsg.InputType.DCP_TUNER); funcNameMap.put("AUX1", InputSelectorMsg.InputType.DCP_AUX1); funcNameMap.put("AUX2", InputSelectorMsg.InputType.DCP_AUX2); funcNameMap.put("AUX3", InputSelectorMsg.InputType.DCP_AUX3); funcNameMap.put("AUX4", InputSelectorMsg.InputType.DCP_AUX4); funcNameMap.put("AUX5", InputSelectorMsg.InputType.DCP_AUX5); funcNameMap.put("AUX6", InputSelectorMsg.InputType.DCP_AUX6); funcNameMap.put("AUX7", InputSelectorMsg.InputType.DCP_AUX7); funcNameMap.put("NETWORK", InputSelectorMsg.InputType.DCP_NET); funcNameMap.put("BLUETOOTH", InputSelectorMsg.InputType.DCP_BT); funcNameMap.put("SOURCE", InputSelectorMsg.InputType.DCP_SOURCE); final InputSelectorMsg.InputType inputType = funcNameMap.get(name.toUpperCase()); if (inputType != null) { Selector oldSelector = null; for (Selector s : this.deviceSelectors) { if (s.getId().equalsIgnoreCase(inputType.getCode())) { oldSelector = s; } } Selector newSelector; if (oldSelector == null) { // Add new selector newSelector = new Selector( inputType.getCode(), defName != null ? defName : name, (int) Math.pow(2, zone), iconId, false); } else { // Update zone of the existing selector newSelector = new Selector( oldSelector, oldSelector.zone + (int) Math.pow(2, zone)); this.deviceSelectors.remove(oldSelector); } this.deviceSelectors.add(newSelector); } else { Logging.info(this, "Input source " + name + " for zone " + zone + " is not implemented"); } } private void parseDcpDeviceCapabilities(Element deviceCapabilities) { // Buttons for RC tab controlList.add("Setup"); controlList.add("Quick"); // Denon-specific capabilities final List<Element> caps = Utils.getElements(deviceCapabilities, "Setup"); if (!caps.isEmpty()) { for (Element cap : Utils.getElements(caps.get(0), null)) { if ("1".equals(Utils.getFirstElementValue(cap, "Control", "0"))) { controlList.add(cap.getTagName()); } } } } private void parseDcpPresets(String dcpPresetData) throws Exception { InputStream stream = new ByteArrayInputStream(dcpPresetData.getBytes(Utils.UTF_8)); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.parse(stream); final Element presetListItem = Utils.getElement(doc, "item"); if (presetListItem == null) { throw new Exception("item section is not found"); } for (Element pl : Utils.getElements(presetListItem, "PresetLists")) { for (Element v : Utils.getElements(pl, "value")) { // <value index="1" skip="OFF" table="01" band="FM" param=" 008830"/> if ("OFF".equalsIgnoreCase(v.getAttribute("skip")) && !"OFF".equalsIgnoreCase(v.getAttribute("table"))) { presetList.add(new Preset(v, ConnectionIf.ProtoType.DCP)); } } } } }
33,479
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
MultiroomGroupSettingMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/MultiroomGroupSettingMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import java.util.ArrayList; import java.util.List; import androidx.annotation.NonNull; /* * Multiroom Group Setting Command */ public class MultiroomGroupSettingMsg extends ISCPMessage { private final static String CODE = "MGS"; public final static int TARGET_ZONE_ID = 1; public enum Command { ADD_SLAVE, GROUP_DISSOLUTION, REMOVE_SLAVE } private final Command command; private final int zone, groupId, maxDelay; private final List<String> devices = new ArrayList<>(); public MultiroomGroupSettingMsg(final Command command, final int zone, final int groupId, final int maxDelay) { super(0, null); this.command = command; this.zone = zone; this.groupId = groupId; this.maxDelay = maxDelay; } @NonNull public List<String> getDevice() { return devices; } @NonNull @Override public String toString() { return CODE + "[" + command.toString() + ", zone=" + zone + ", groupId=" + groupId + ", maxDelay=" + maxDelay + "]"; } @SuppressWarnings("StringBufferReplaceableByString") @Override public EISCPMessage getCmdMsg() { switch (command) { case ADD_SLAVE: { final StringBuilder cmd = new StringBuilder(); cmd.append("<mgs zone=\""); cmd.append(zone); cmd.append("\"><groupid>"); cmd.append(groupId); cmd.append("</groupid><maxdelay>"); cmd.append(maxDelay); cmd.append("</maxdelay><devices>"); for (String d : devices) { cmd.append("<device id=\"").append(d).append("\" zoneid=\"1\"/>"); } cmd.append("</devices></mgs>"); return new EISCPMessage(CODE, cmd.toString()); } case GROUP_DISSOLUTION: { final StringBuilder cmd = new StringBuilder(); cmd.append("<mgs zone=\""); cmd.append(zone); cmd.append("\"><groupid>"); cmd.append(groupId); cmd.append("</groupid></mgs>"); return new EISCPMessage(CODE, cmd.toString()); } case REMOVE_SLAVE: { final StringBuilder cmd = new StringBuilder(); cmd.append("<mgs zone=\""); cmd.append(zone); cmd.append("\"><groupid>"); cmd.append(groupId); cmd.append("</groupid><maxdelay>"); cmd.append(maxDelay); cmd.append("</maxdelay><devices>"); for (String d : devices) { cmd.append("<device id=\"").append(d).append("\" zoneid=\"" + TARGET_ZONE_ID + "\"/>"); } cmd.append("</devices></mgs>"); return new EISCPMessage(CODE, cmd.toString()); } } return null; } @Override public boolean hasImpactOnMediaList() { return false; } }
3,864
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
MultiroomChannelSettingMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/MultiroomChannelSettingMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; import static com.mkulesh.onpc.iscp.messages.MultiroomDeviceInformationMsg.ChannelType; /* * Multiroom Speaker (Channel) Setting Command */ public class MultiroomChannelSettingMsg extends ISCPMessage { public final static String CODE = "MSS"; private int zone; private ChannelType channelType; MultiroomChannelSettingMsg(EISCPMessage raw) throws Exception { super(raw); try { zone = Integer.parseInt(data.substring(0, 1), 10); channelType = ChannelType.valueOf(data.substring(1)); } catch (Exception e) { zone = 0; channelType = ChannelType.NONE; } } public MultiroomChannelSettingMsg(int zone, ChannelType channelType) { super(0, null); this.zone = zone; this.channelType = channelType; } public ChannelType getChannelType() { return channelType; } @NonNull @Override public String toString() { return CODE + "[zone=" + zone + ", type=" + channelType.toString() + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, zone + channelType.toString()); } @Override public boolean hasImpactOnMediaList() { return false; } public static ChannelType getUpType(ChannelType ch) { switch (ch) { case FL: return ChannelType.FR; case FR: return ChannelType.ST; case ST: return ChannelType.FL; default: return ch; } } }
2,459
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
MenuStatusMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/MenuStatusMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; /* * NET/USB Menu Status */ public class MenuStatusMsg extends ISCPMessage { public final static String CODE = "NMS"; /* * Track Menu: "M": Menu is enable, "x": Menu is disable */ public enum TrackMenu implements CharParameterIf { ENABLE('M'), DISABLE('x'); final Character code; TrackMenu(Character code) { this.code = code; } public Character getCode() { return code; } } private TrackMenu trackMenu = TrackMenu.DISABLE; /* * Feed: "xx":disable, "01":Like, "02":don't like, "03":Love, "04":Ban, * "05":episode, "06":ratings, "07":Ban(black), "08":Ban(white), * "09":Favorite(black), "0A":Favorite(white), "0B":Favorite(yellow) */ public enum Feed implements StringParameterIf { DISABLE("XX", -1), LIKE("01", R.drawable.feed_like), DONT_LIKE("02", R.drawable.feed_dont_like), LOVE("03", R.drawable.feed_love), BAN("04", R.drawable.feed_ban), EPISODE("05", -1), RATINGS("06", -1), BAN_BLACK("07", R.drawable.feed_ban), BAN_WHITE("08", R.drawable.feed_ban), FAVORITE_BLACK("09", R.drawable.feed_love), FAVORITE_WHITE("0A", R.drawable.feed_love), FAVORITE_YELLOW("0B", R.drawable.feed_love), LIKE_AMAZON("0C", R.drawable.feed_like); final String code; @DrawableRes final int imageId; Feed(String code, @DrawableRes final int imageId) { this.code = code; this.imageId = imageId; } public String getCode() { return code; } @DrawableRes public int getImageId() { return imageId; } public boolean isImageValid() { return imageId != -1; } } private Feed positiveFeed = Feed.DISABLE; private Feed negativeFeed = Feed.DISABLE; /* * Time Seek "S": Time Seek is enable "x": Time Seek is disable */ public enum TimeSeek implements CharParameterIf { ENABLE('S'), DISABLE('x'); final Character code; TimeSeek(Character code) { this.code = code; } public Character getCode() { return code; } } private TimeSeek timeSeek = TimeSeek.DISABLE; /* * Time Display "1": Elapsed Time/Total Time, "2": Elapsed Time, "x": disable */ private enum TimeDisplay implements CharParameterIf { ELAPSED_TOTAL('1'), ELAPSED('2'), DISABLE('x'); final Character code; TimeDisplay(Character code) { this.code = code; } public Character getCode() { return code; } } private TimeDisplay timeDisplay = TimeDisplay.DISABLE; private ServiceType serviceIcon = ServiceType.UNKNOWN; MenuStatusMsg(EISCPMessage raw) throws Exception { super(raw); /* NET/USB Menu Status (9 letters) m -> Track Menu: "M": Menu is enable, "x": Menu is disable aa -> F1 button icon (Positive Feed or Mark/Unmark) bb -> F2 button icon (Negative Feed) s -> Time Seek "S": Time Seek is enable "x": Time Seek is disable t -> Time Display "1": Elapsed Time/Total Time, "2": Elapsed Time, "x": disable ii-> Service icon */ final String format = "maabbstii"; if (data.length() >= format.length()) { trackMenu = (TrackMenu) searchParameter(data.charAt(0), TrackMenu.values(), trackMenu); positiveFeed = (Feed) searchParameter(data.substring(1, 3), Feed.values(), positiveFeed); negativeFeed = (Feed) searchParameter(data.substring(3, 5), Feed.values(), negativeFeed); timeSeek = (TimeSeek) searchParameter(data.charAt(5), TimeSeek.values(), timeSeek); timeDisplay = (TimeDisplay) searchParameter(data.charAt(6), TimeDisplay.values(), timeDisplay); serviceIcon = (ServiceType) searchParameter(data.substring(7, 9), ServiceType.values(), serviceIcon); } } public TrackMenu getTrackMenu() { return trackMenu; } public TimeSeek getTimeSeek() { return timeSeek; } public ServiceType getServiceIcon() { return serviceIcon; } public Feed getPositiveFeed() { return positiveFeed; } public Feed getNegativeFeed() { return negativeFeed; } @NonNull @Override public String toString() { return CODE + "[" + data + "; TRACK_MENU=" + trackMenu.toString() + "; POS_FEED=" + positiveFeed.toString() + "; NEG_FEED=" + negativeFeed.toString() + "; TIME_SEEK=" + timeSeek.toString() + "; TIME_DISPLAY=" + timeDisplay.toString() + "; ICON=" + serviceIcon.toString() + "]"; } }
5,973
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
ToneCommandMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/ToneCommandMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import android.annotation.SuppressLint; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ZonedMessage; import com.mkulesh.onpc.utils.Logging; import com.mkulesh.onpc.utils.Utils; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /* * Tone/Front (for main zone) and Tone (for zones 2, 3) command */ @SuppressWarnings({ "DuplicateExpressions", "RedundantSuppression" }) public class ToneCommandMsg extends ZonedMessage { final static String CODE = "TFR"; final static String ZONE2_CODE = "ZTN"; final static String ZONE3_CODE = "TN3"; // Tone command is not available for zone 4 public final static String[] ZONE_COMMANDS = new String[]{ CODE, ZONE2_CODE, ZONE3_CODE }; public final static int NO_LEVEL = 0xFF; private final boolean tonJoined; public final static String BASS_KEY = "Bass"; private final static Character BASS_MARKER = 'B'; private int bassLevel = NO_LEVEL; public final static String TREBLE_KEY = "Treble"; private final static Character TREBLE_MARKER = 'T'; private int trebleLevel = NO_LEVEL; ToneCommandMsg(EISCPMessage raw) throws Exception { super(raw, ZONE_COMMANDS); tonJoined = true; for (int i = 0; i < data.length(); i++) { if (data.charAt(i) == BASS_MARKER && data.length() > i + 2) { try { if (data.charAt(i + 1) == '+') { bassLevel = Integer.parseInt(data.substring(i + 2, i + 3), 16); } else if (data.charAt(i + 1) == '-') { bassLevel = -Integer.parseInt(data.substring(i + 2, i + 3), 16); } else { bassLevel = Integer.parseInt(data.substring(i + 1, i + 3), 16); } } catch (Exception e) { bassLevel = NO_LEVEL; } } if (data.charAt(i) == TREBLE_MARKER && data.length() > i + 2) { try { if (data.charAt(i + 1) == '+') { trebleLevel = Integer.parseInt(data.substring(i + 2, i + 3), 16); } else if (data.charAt(i + 1) == '-') { trebleLevel = -Integer.parseInt(data.substring(i + 2, i + 3), 16); } else { trebleLevel = Integer.parseInt(data.substring(i + 1, i + 3), 16); } } catch (Exception e) { trebleLevel = NO_LEVEL; } } } } public ToneCommandMsg(int zoneIndex, int bass, int treble) { super(0, null, zoneIndex); tonJoined = false; this.bassLevel = bass; this.trebleLevel = treble; } @Override public String getZoneCommand() { return ZONE_COMMANDS[zoneIndex]; } public boolean isTonJoined() { return tonJoined; } public int getBassLevel() { return bassLevel; } public int getTrebleLevel() { return trebleLevel; } @NonNull @Override public String toString() { return getZoneCommand() + "[" + data + "; ZONE_INDEX=" + zoneIndex + "; BASS=" + bassLevel + "; TREBLE=" + trebleLevel + "]"; } @Override public EISCPMessage getCmdMsg() { String par = ""; if (bassLevel != NO_LEVEL) { par += Utils.intToneToString(BASS_MARKER, bassLevel); } if (trebleLevel != NO_LEVEL) { par += Utils.intToneToString(TREBLE_MARKER, trebleLevel); } return new EISCPMessage(getZoneCommand(), par); } @Override public boolean hasImpactOnMediaList() { return false; } /* * Denon control protocol */ public static ToneCommandMsg processDcpMessage(@NonNull String dcpMsg) { // Bass for (int i = 0; i < DcpReceiverInformationMsg.DCP_COMMANDS_BASS.length; i++) { if (dcpMsg.startsWith(DcpReceiverInformationMsg.DCP_COMMANDS_BASS[i])) { final String par = dcpMsg.substring( DcpReceiverInformationMsg.DCP_COMMANDS_BASS[i].length()).trim(); try { final int level = Integer.parseInt(par) - DcpReceiverInformationMsg.DCP_TON_SHIFT[i]; return new ToneCommandMsg(i, level, NO_LEVEL); } catch (Exception e) { Logging.info(ToneCommandMsg.class, "Unable to parse bass level " + par); return null; } } } // Treble for (int i = 0; i < DcpReceiverInformationMsg.DCP_COMMANDS_TREBLE.length; i++) { if (dcpMsg.startsWith(DcpReceiverInformationMsg.DCP_COMMANDS_TREBLE[i])) { final String par = dcpMsg.substring( DcpReceiverInformationMsg.DCP_COMMANDS_TREBLE[i].length()).trim(); try { final int level = Integer.parseInt(par) - DcpReceiverInformationMsg.DCP_TON_SHIFT[i]; return new ToneCommandMsg(i, NO_LEVEL, level); } catch (Exception e) { Logging.info(ToneCommandMsg.class, "Unable to parse treble level " + par); return null; } } } return null; } @Nullable @Override @SuppressLint("DefaultLocale") public String buildDcpMsg(boolean isQuery) { if (isQuery) { final String bassReq = DcpReceiverInformationMsg.DCP_COMMANDS_BASS[zoneIndex] + " " + DCP_MSG_REQ; final String trebleReq = DcpReceiverInformationMsg.DCP_COMMANDS_TREBLE[zoneIndex] + " " + DCP_MSG_REQ; return bassReq + DCP_MSG_SEP + trebleReq; } else if (bassLevel != NO_LEVEL) { final String par = String.format("%02d", bassLevel + DcpReceiverInformationMsg.DCP_TON_SHIFT[zoneIndex]); return DcpReceiverInformationMsg.DCP_COMMANDS_BASS[zoneIndex] + " " + par; } else if (trebleLevel != NO_LEVEL) { final String par = String.format("%02d", trebleLevel + DcpReceiverInformationMsg.DCP_TON_SHIFT[zoneIndex]); return DcpReceiverInformationMsg.DCP_COMMANDS_TREBLE[zoneIndex] + " " + par; } return null; } }
7,661
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
XmlListInfoMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/XmlListInfoMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import com.mkulesh.onpc.utils.Utils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import androidx.annotation.NonNull; /* * NET/USB List Info(All item, need processing XML data, for Network Control Only) */ public class XmlListInfoMsg extends ISCPMessage { public final static String CODE = "NLA"; private final Character responseType; private final int sequenceNumber; private final Character status; /* * UI type '0' : List, '1' : Menu, '2' : Playback, '3' : Popup, '4' : Keyboard, "5" : Menu List */ private enum UiType implements CharParameterIf { LIST('0'), MENU('1'), PLAYBACK('2'), POPUP('3'), KEYBOARD('4'), MENU_LIST('5'); final Character code; UiType(Character code) { this.code = code; } public Character getCode() { return code; } } private final UiType uiType; private final String rawXml; XmlListInfoMsg(EISCPMessage raw) throws Exception { super(raw); // Format: "tzzzzsurr<.....>" responseType = data.charAt(0); sequenceNumber = Integer.parseInt(data.substring(1, 5), 16); status = data.charAt(5); uiType = (UiType) searchParameter(data.charAt(6), UiType.values(), UiType.LIST); rawXml = data.substring(9); } @NonNull @Override public String toString() { return CODE + "[" + data.substring(0, 9) + "..." + "; RESP=" + responseType + "; SEQ_NR=" + sequenceNumber + "; STATUS=" + status + "; UI=" + uiType.toString() + "; " + (isMultiline() ? ("XML<" + rawXml.length() + "B>") : ("XML=" + rawXml)) + "]"; } public static String getListedData(int seqNumber, int layer, int startItem, int endItem) { return "L" + String.format("%04x", seqNumber) + String.format("%02x", layer) + String.format("%04x", startItem) + String.format("%04x", endItem); } public void parseXml(final List<XmlListItemMsg> items, final int numberOfLayers) throws Exception { items.clear(); InputStream stream = new ByteArrayInputStream(rawXml.getBytes(Utils.UTF_8)); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.parse(stream); for (Node object = doc.getDocumentElement(); object != null; object = object.getNextSibling()) { if (object instanceof Element) { final Element response = (Element) object; if (!response.getTagName().equals("response") || !Utils.ensureAttribute(response, "status", "ok")) { continue; } final List<Element> itemsTop = Utils.getElements(response, "items"); if (itemsTop.isEmpty()) { continue; } // Only process the first "items" element Element itemsInfo = itemsTop.get(0); if (itemsInfo == null || itemsInfo.getAttribute("offset") == null || itemsInfo.getAttribute("totalitems") == null) { continue; } int offset = Integer.parseInt(itemsInfo.getAttribute("offset")); final List<Element> elements = Utils.getElements(itemsInfo, "item"); int id = 0; for (Element element : elements) { items.add(new XmlListItemMsg(offset + id, numberOfLayers, element)); id++; } } } stream.close(); } }
4,873
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
SleepSetCommandMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/SleepSetCommandMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import android.annotation.SuppressLint; import com.mkulesh.onpc.iscp.ConnectionIf; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import java.util.ArrayList; import java.util.Collections; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /* * Sleep Set Command */ public class SleepSetCommandMsg extends ISCPMessage { public final static String CODE = "SLP"; public final static int NOT_APPLICABLE = 0xFF; public final static int SLEEP_OFF = 0x00; private int sleepTime; SleepSetCommandMsg(EISCPMessage raw) throws Exception { super(raw); try { sleepTime = "OFF".equals(data) ? SLEEP_OFF : Integer.parseInt(data, 16); } catch (Exception e) { sleepTime = NOT_APPLICABLE; } } public SleepSetCommandMsg(int sleepTime) { super(0, null); this.sleepTime = sleepTime; } public int getSleepTime() { return sleepTime; } @NonNull @Override public String toString() { return CODE + "[" + data + "; SLEEP_TIME=" + sleepTime + "min]"; } @Override public EISCPMessage getCmdMsg() { final String cmd = sleepTime == SLEEP_OFF ? "OFF" : String.format("%02x", sleepTime); return new EISCPMessage(CODE, cmd); } @Override public boolean hasImpactOnMediaList() { return false; } public static int toggle(int sleepTime, ProtoType protoType) { final int max = protoType == ConnectionIf.ProtoType.ISCP ? 90 : 120; final int res = 15 * ((int) ((float) sleepTime / 15.0) + 1); return res > max ? 0 : res; } /* * Denon control protocol */ private final static String DCP_COMMAND = "SLP"; @NonNull public static ArrayList<String> getAcceptedDcpCodes() { return new ArrayList<>(Collections.singletonList(DCP_COMMAND)); } @Nullable public static SleepSetCommandMsg processDcpMessage(@NonNull String dcpMsg) { if (dcpMsg.startsWith(DCP_COMMAND)) { final String par = dcpMsg.substring(DCP_COMMAND.length()).trim(); try { return new SleepSetCommandMsg("OFF".equals(par) ? SLEEP_OFF : Integer.parseInt(par)); } catch (Exception e) { return null; } } return null; } @SuppressLint("DefaultLocale") @Nullable @Override public String buildDcpMsg(boolean isQuery) { return DCP_COMMAND + (isQuery ? DCP_MSG_REQ : sleepTime == SLEEP_OFF ? "OFF" : String.format("%03d", sleepTime)); } }
3,468
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
TrackInfoMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/TrackInfoMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; /* * NET/USB Track Info */ public class TrackInfoMsg extends ISCPMessage { public final static String CODE = "NTR"; /* * (Current Track/Total Track Max 9999. If Track is unknown, this response is ----) */ private Integer currentTrack, maxTrack; TrackInfoMsg(EISCPMessage raw) throws Exception { super(raw); final String[] pars = data.split(PAR_SEP); if (pars.length != 2) { throw new Exception("Can not find parameter split character in message " + raw); } try { currentTrack = Integer.parseInt(pars[0]); } catch (Exception e) { currentTrack = null; } try { maxTrack = Integer.parseInt(pars[1]); } catch (Exception e) { maxTrack = null; } } public Integer getCurrentTrack() { return currentTrack; } public Integer getMaxTrack() { return maxTrack; } @NonNull @Override public String toString() { return CODE + "[" + currentTrack + "; " + maxTrack + "]"; } }
2,000
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
AudioInformationMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/AudioInformationMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; /* * Audio Information Command message */ public class AudioInformationMsg extends ISCPMessage { public final static String CODE = "IFA"; /* * Information of Audio(Same Immediate Display ',' is separator of informations) * a...a: Audio Input Port * b…b: Input Signal Format * c…c: Sampling Frequency * d…d: Input Signal Channel * e…e: Listening Mode * f…f: Output Signal Channel * g…g: Output Sampling Frequency * h...h: PQLS (Off/2ch/Multich/Bitstream) * i...i: Auto Phase Control Current Delay (0ms - 16ms / ---) * j...j: Auto Phase Control Phase (Normal/Reverse) * k...k: Upmix Mode(No/PL2/PL2X/PL2Z/DolbySurround/Neo6/NeoX/NeuralX/THXS2/ADYDSX) */ public final String audioInput; public final String audioOutput; AudioInformationMsg(EISCPMessage raw) throws Exception { super(raw); final String[] pars = data.split(COMMA_SEP); audioInput = getTags(pars, 0, 5); audioOutput = getTags(pars, 5, pars.length); } @NonNull @Override public String toString() { return CODE + "[" + getData() + "; IN=" + audioInput + "; OUT=" + audioOutput + "]"; } }
2,054
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
MusicOptimizerMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/MusicOptimizerMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /* * Music Optimizer Command */ public class MusicOptimizerMsg extends ISCPMessage { public final static String CODE = "MOT"; public enum Status implements StringParameterIf { NONE("N/A", R.string.device_two_way_switch_none), OFF("00", R.string.device_two_way_switch_off), ON("01", R.string.device_two_way_switch_on), TOGGLE("UP", R.string.device_two_way_switch_toggle); final String code; @StringRes final int descriptionId; Status(final String code, @StringRes final int descriptionId) { this.code = code; this.descriptionId = descriptionId; } public String getCode() { return code; } @StringRes public int getDescriptionId() { return descriptionId; } } private final Status status; MusicOptimizerMsg(EISCPMessage raw) throws Exception { super(raw); status = (Status) searchParameter(data, Status.values(), Status.NONE); } public MusicOptimizerMsg(Status level) { super(0, null); this.status = level; } public Status getStatus() { return status; } @NonNull @Override public String toString() { return CODE + "[" + status.toString() + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, status.getCode()); } @Override public boolean hasImpactOnMediaList() { return false; } }
2,479
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
DigitalFilterMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/DigitalFilterMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /* * Dimmer Level Command */ public class DigitalFilterMsg extends ISCPMessage { public final static String CODE = "DGF"; public enum Filter implements StringParameterIf { NONE("N/A", R.string.device_digital_filter_none), F00("00", R.string.device_digital_filter_slow), F01("01", R.string.device_digital_filter_sharp), F02("02", R.string.device_digital_filter_short), TOGGLE("UP", R.string.device_digital_filter_toggle); final String code; @StringRes final int descriptionId; Filter(final String code, @StringRes final int descriptionId) { this.code = code; this.descriptionId = descriptionId; } public String getCode() { return code; } @StringRes public int getDescriptionId() { return descriptionId; } } private final Filter filter; DigitalFilterMsg(EISCPMessage raw) throws Exception { super(raw); filter = (Filter) searchParameter(data, Filter.values(), Filter.NONE); } public DigitalFilterMsg(Filter level) { super(0, null); this.filter = level; } public Filter getFilter() { return filter; } @NonNull @Override public String toString() { return CODE + "[" + filter.getCode() + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, filter.getCode()); } @Override public boolean hasImpactOnMediaList() { return false; } }
2,534
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
SetupOperationCommandMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/SetupOperationCommandMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; /* * Setup Operation Command */ public class SetupOperationCommandMsg extends ISCPMessage { public final static String CODE = "OSD"; public enum Command implements DcpStringParameterIf { MENU("MENU", "MEN ON", R.string.cmd_description_setup, R.drawable.cmd_setup), UP("UP", "CUP", R.string.cmd_description_up, R.drawable.cmd_up), DOWN("DOWN", "CDN", R.string.cmd_description_down, R.drawable.cmd_down), RIGHT("RIGHT", "CRT", R.string.cmd_description_right, R.drawable.cmd_right), LEFT("LEFT", "CLT", R.string.cmd_description_left, R.drawable.cmd_left), ENTER("ENTER", "ENT", R.string.cmd_description_select, R.drawable.cmd_select), EXIT("EXIT", "RTN", R.string.cmd_description_return, R.drawable.cmd_return), HOME("HOME", "N/A", R.string.cmd_description_home, R.drawable.cmd_home), QUICK("QUICK", "OPT", R.string.cmd_description_quick_menu, R.drawable.cmd_quick_menu); final String code, dcpCode; @StringRes final int descriptionId; @DrawableRes final int imageId; Command(final String code, final String dcpCode, @StringRes final int descriptionId, @DrawableRes final int imageId) { this.code = code; this.dcpCode = dcpCode; this.descriptionId = descriptionId; this.imageId = imageId; } public String getCode() { return code; } @NonNull public String getDcpCode() { return dcpCode; } @StringRes public int getDescriptionId() { return descriptionId; } @DrawableRes public int getImageId() { return imageId; } } private final Command command; SetupOperationCommandMsg(EISCPMessage raw) throws Exception { super(raw); this.command = (Command) searchParameter(data, Command.values(), Command.HOME); } public SetupOperationCommandMsg(final String command) { super(0, null); this.command = (Command) searchParameter(command, Command.values(), null); } public Command getCommand() { return command; } @NonNull @Override public String toString() { return CODE + "[" + data + "; CMD=" + (command == null ? "null" : command.toString()) + "]"; } @Override public EISCPMessage getCmdMsg() { return command == null ? null : new EISCPMessage(CODE, command.getCode()); } @Override public boolean hasImpactOnMediaList() { return false; } /* * Denon control protocol */ private final static String DCP_COMMAND = "MN"; @Nullable @Override public String buildDcpMsg(boolean isQuery) { return (command != null && !isQuery) ? DCP_COMMAND + command.getDcpCode() : null; } }
3,938
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
BroadcastResponseMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/BroadcastResponseMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.iscp.ConnectionIf; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import java.net.InetAddress; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /* * Broadcast Response Message * * !cECNnnnnnn/ppppp/dd/iiiiiiiiiiii: * c: device category * nnnnnnn: model name of device * ppppp: ISCP port number * dd: destination area of device * iiiiiiiiiiii: Identifier * /: Separator */ public class BroadcastResponseMsg extends ISCPMessage { private final static String CODE = "ECN"; private String model = null; private String destinationArea = null; private String identifier = null; private String alias = null; public BroadcastResponseMsg(InetAddress hostAddress, EISCPMessage raw) throws Exception { super(raw); host = hostAddress.getHostAddress(); String[] tokens = data.split("/"); if (tokens.length > 0) { model = tokens[0]; } if (tokens.length > 1) { port = Integer.parseInt(tokens[1], 10); } if (tokens.length > 2) { destinationArea = tokens[2]; } if (tokens.length > 3) { identifier = tokens[3]; } } public BroadcastResponseMsg(BroadcastResponseMsg other) { super(other); this.model = other.model; this.port = other.port; this.destinationArea = other.destinationArea; this.identifier = other.identifier; this.alias = other.alias; } public BroadcastResponseMsg(@NonNull final String host, final int port, @NonNull final String alias, @Nullable final String identifier) { super(0, null); this.host = host; this.port = port; this.alias = alias; this.identifier = identifier; // all other fields still be null } public BroadcastResponseMsg(@NonNull final String host, final int port, @NonNull final String model) { super(0, null); this.host = host; this.port = port; this.model = model; // all other fields still be null } @NonNull @Override public String toString() { return CODE + "[" + data + "; HOST=" + getHostAndPort() + "; " + getProtoType() + (model != null ? "; MODEL=" + model : "") + (destinationArea != null ? "; DST=" + destinationArea : "") + (identifier != null ? "; ID=" + identifier : "") + (alias != null ? "; ALIAS=" + alias : "") + "]"; } @NonNull public String getDescription() { final String d = alias != null ? alias : (model != null ? model : "unknown"); return getHost() + "/" + d; } @NonNull public String getIdentifier() { return identifier == null ? "" : identifier; } @Nullable public String getAlias() { return alias; } public ProtoType getProtoType() { return port == DCP_PORT ? ConnectionIf.ProtoType.DCP : ConnectionIf.ProtoType.ISCP; } }
3,948
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
FileFormatMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/FileFormatMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import androidx.annotation.NonNull; /* * NET/USB File Info (variable-length, 64 ASCII letters max) */ public class FileFormatMsg extends ISCPMessage { public final static String CODE = "NFI"; private final String format, sampleFrequency, bitRate; FileFormatMsg(EISCPMessage raw) throws Exception { super(raw); final String[] pars = data.split(PAR_SEP); format = pars.length > 0 ? pars[0] : ""; sampleFrequency = pars.length > 1 ? pars[1] : ""; bitRate = pars.length > 2 ? pars[2] : ""; } public String getFullFormat() { final StringBuilder str = new StringBuilder(); str.append(format); if (!str.toString().isEmpty() && !sampleFrequency.isEmpty()) { str.append("/"); } str.append(sampleFrequency); if (!str.toString().isEmpty() && !bitRate.isEmpty()) { str.append("/"); } str.append(bitRate); return str.toString(); } @NonNull @Override public String toString() { return CODE + "[" + data + "; FORMAT=" + format + "; FREQUENCY=" + sampleFrequency + "; BITRATE=" + bitRate + "]"; } }
2,067
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
FriendlyNameMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/FriendlyNameMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.jayway.jsonpath.JsonPath; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import java.util.ArrayList; import java.util.Collections; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /* * Friendly Name Setting Command */ public class FriendlyNameMsg extends ISCPMessage { public final static String CODE = "NFN"; private final String friendlyName; FriendlyNameMsg(EISCPMessage raw) throws Exception { super(raw); String str = ""; if (data != null && !data.equals(".")) { str = data.startsWith(".") ? data.substring(1) : data; } friendlyName = str.trim(); } public FriendlyNameMsg(String name) { super(0, null); this.friendlyName = name; } public String getFriendlyName() { return friendlyName; } @NonNull @Override public String toString() { return CODE + "[" + friendlyName + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, friendlyName.isEmpty() ? " " : friendlyName); } @Override public boolean hasImpactOnMediaList() { return false; } /* * Denon control protocol * Command: heos://player/get_player_info?pid=player_id * Response: {"heos": {"command": "player/get_player_info", "result": "success", "message": "pid=-2078441090"}, * "payload": {"name": "Denon Player", "pid": -2078441090, ...}} * Change: NSFRN */ private final static String HEOS_COMMAND = "player/get_player_info"; private final static String DCP_COMMAND = "NSFRN"; @NonNull public static ArrayList<String> getAcceptedDcpCodes() { return new ArrayList<>(Collections.singletonList(DCP_COMMAND)); } @Nullable public static FriendlyNameMsg processDcpMessage(@NonNull String dcpMsg) { return dcpMsg.startsWith(DCP_COMMAND) ? new FriendlyNameMsg(dcpMsg.substring(DCP_COMMAND.length()).trim()) : null; } @Nullable public static FriendlyNameMsg processHeosMessage(@NonNull final String command, @NonNull final String heosMsg) { if (HEOS_COMMAND.equals(command)) { final String name = JsonPath.read(heosMsg, "$.payload.name"); return name != null ? new FriendlyNameMsg(name) : null; } return null; } @Nullable @Override public String buildDcpMsg(boolean isQuery) { return isQuery ? "heos://" + HEOS_COMMAND + "?pid=" + ISCPMessage.DCP_HEOS_PID : (DCP_COMMAND + " " + friendlyName); } }
3,419
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
DimmerLevelMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/DimmerLevelMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import java.util.ArrayList; import java.util.Collections; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; /* * Dimmer Level Command */ public class DimmerLevelMsg extends ISCPMessage { public final static String CODE = "DIM"; public enum Level implements DcpStringParameterIf { NONE("N/A", "N/A", R.string.device_dimmer_level_none), BRIGHT("00", "BRI", R.string.device_dimmer_level_bright), DIM("01", "DIM", R.string.device_dimmer_level_dim), DARK("02", "DAR", R.string.device_dimmer_level_dark), SHUT_OFF("03", "N/A", R.string.device_dimmer_level_shut_off), OFF("08", "OFF", R.string.device_dimmer_level_off), TOGGLE("DIM", "SEL", R.string.device_dimmer_level_toggle); final String code, dcpCode; @StringRes final int descriptionId; Level(final String code, final String dcpCode, @StringRes final int descriptionId) { this.code = code; this.dcpCode = dcpCode; this.descriptionId = descriptionId; } public String getCode() { return code; } @NonNull public String getDcpCode() { return dcpCode; } @StringRes public int getDescriptionId() { return descriptionId; } } private final Level level; DimmerLevelMsg(EISCPMessage raw) throws Exception { super(raw); level = (Level) searchParameter(data, Level.values(), Level.NONE); } public DimmerLevelMsg(Level level) { super(0, null); this.level = level; } public Level getLevel() { return level; } @NonNull @Override public String toString() { return CODE + "[" + level.getCode() + "]"; } @Override public EISCPMessage getCmdMsg() { return new EISCPMessage(CODE, level.getCode()); } @Override public boolean hasImpactOnMediaList() { return false; } /* * Denon control protocol */ private final static String DCP_COMMAND = "DIM"; @NonNull public static ArrayList<String> getAcceptedDcpCodes() { return new ArrayList<>(Collections.singletonList(DCP_COMMAND)); } @Nullable public static DimmerLevelMsg processDcpMessage(@NonNull String dcpMsg) { final Level s = (Level) searchDcpParameter(DCP_COMMAND, dcpMsg, Level.values()); return s != null ? new DimmerLevelMsg(s) : null; } @Nullable @Override public String buildDcpMsg(boolean isQuery) { // A space is needed for this command return DCP_COMMAND + " " + (isQuery ? DCP_MSG_REQ : level.getDcpCode()); } }
3,657
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
PlayStatusMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/PlayStatusMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import java.util.Map; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /* * NET/USB/CD Play Status (3 letters) */ public class PlayStatusMsg extends ISCPMessage { public final static String CODE = "NST"; public final static String CD_CODE = "CST"; public enum UpdateType { ALL, PLAY_STATE, PLAY_MODE, REPEAT, SHUFFLE } final private UpdateType updateType; /* * Play Status: "S": STOP, "P": Play, "p": Pause, "F": FF, "R": FR, "E": EOF */ public enum PlayStatus implements DcpCharParameterIf { STOP('S'), PLAY('P'), PAUSE('p'), FF('F'), FR('R'), EOF('E'); final Character code; PlayStatus(Character code) { this.code = code; } public Character getCode() { return code; } @NonNull @Override public String getDcpCode() { return name(); } } private PlayStatus playStatus = PlayStatus.EOF; /* * Repeat Status: "-": Off, "R": All, "F": Folder, "1": Repeat 1, "x": disable */ public enum RepeatStatus implements DcpCharParameterIf { OFF('-', "off", R.drawable.repeat_off), ALL('R', "on_all", R.drawable.repeat_all), FOLDER('F', "NONE", R.drawable.repeat_folder), REPEAT_1('1', "on_one", R.drawable.repeat_once), DISABLE('x', "NONE", R.drawable.repeat_off); final Character code; final String dcpCode; @DrawableRes final int imageId; RepeatStatus(Character code, String dcpCode, @DrawableRes final int imageId) { this.code = code; this.dcpCode = dcpCode; this.imageId = imageId; } public Character getCode() { return code; } @DrawableRes public int getImageId() { return imageId; } @NonNull @Override public String getDcpCode() { return dcpCode; } } private RepeatStatus repeatStatus = RepeatStatus.DISABLE; /* * Shuffle Status: "-": Off, "S": All , "A": Album, "F": Folder, "x": disable */ public enum ShuffleStatus implements DcpCharParameterIf { OFF('-', "off"), ALL('S', "on"), ALBUM('A', "NONE"), FOLDER('F', "NONE"), DISABLE('x', "NONE"); final Character code; final String dcpCode; ShuffleStatus(Character code, String dcpCode) { this.code = code; this.dcpCode = dcpCode; } public Character getCode() { return code; } @NonNull @Override public String getDcpCode() { return dcpCode; } } private ShuffleStatus shuffleStatus = ShuffleStatus.DISABLE; PlayStatusMsg(EISCPMessage raw) throws Exception { super(raw); updateType = UpdateType.ALL; if (data.length() > 0) { playStatus = (PlayStatus) searchParameter(data.charAt(0), PlayStatus.values(), playStatus); } if (data.length() > 1) { repeatStatus = (RepeatStatus) searchParameter(data.charAt(1), RepeatStatus.values(), repeatStatus); } if (data.length() > 2) { shuffleStatus = (ShuffleStatus) searchParameter(data.charAt(2), ShuffleStatus.values(), shuffleStatus); } } PlayStatusMsg(PlayStatus playStatus) { super(0, null); this.updateType = UpdateType.PLAY_STATE; this.playStatus = playStatus; } PlayStatusMsg(RepeatStatus repeatStatus, ShuffleStatus shuffleStatus) { super(0, null); this.updateType = UpdateType.PLAY_MODE; this.repeatStatus = repeatStatus; this.shuffleStatus = shuffleStatus; } PlayStatusMsg(RepeatStatus repeatStatus) { super(0, null); this.updateType = UpdateType.REPEAT; this.repeatStatus = repeatStatus; } PlayStatusMsg(ShuffleStatus shuffleStatus) { super(0, null); this.updateType = UpdateType.SHUFFLE; this.shuffleStatus = shuffleStatus; } public UpdateType getUpdateType() { return updateType; } public PlayStatus getPlayStatus() { return playStatus; } public RepeatStatus getRepeatStatus() { return repeatStatus; } public ShuffleStatus getShuffleStatus() { return shuffleStatus; } @NonNull @Override public String toString() { return CODE + "[" + data + "; PLAY=" + playStatus.toString() + "; REPEAT=" + repeatStatus.toString() + "; SHUFFLE=" + shuffleStatus.toString() + "]"; } /* * Denon control protocol * - Player State Changed * { * "heos": { * "command": "event/player_state_changed", * "message": "pid='player_id'&state='play_state'" * } * } * - Get Play State: heos://player/get_play_state?pid=player_id * { * "heos": { * "command": "player/get_play_state", * "result": "success", * "message": "pid='player_id'&state='play_state'" * } * } * - Get Play Mode: heos://player/get_play_mode?pid=player_id * - Player Repeat Mode Changed * { * "heos": { * "command": "event/repeat_mode_changed", * "message": "pid=’player_id’&repeat='on_all_or_on_one_or_off'” * } * } * - Player Shuffle Mode Changed * { * "heos": { * "command": "event/shuffle_mode_changed", * "message": "pid=’player_id’&shuffle='on_or_off'” * } * } */ private final static String HEOS_EVENT_STATE = "event/player_state_changed"; private final static String HEOS_EVENT_REPEAT = "event/repeat_mode_changed"; private final static String HEOS_EVENT_SHUFFLE = "event/shuffle_mode_changed"; private final static String HEOS_COMMAND_STATE = "player/get_play_state"; private final static String HEOS_COMMAND_MODE = "player/get_play_mode"; @Nullable public static PlayStatusMsg processHeosMessage(@NonNull final String command, @NonNull final Map<String, String> tokens) { if (HEOS_EVENT_STATE.equals(command) || HEOS_EVENT_REPEAT.equals(command) || HEOS_EVENT_SHUFFLE.equals(command) || HEOS_COMMAND_STATE.equals(command) || HEOS_COMMAND_MODE.equals(command)) { if (HEOS_EVENT_STATE.equals(command) || HEOS_COMMAND_STATE.equals(command)) { final PlayStatus s = (PlayStatus) searchDcpParameter(tokens.get("state"), PlayStatus.values()); if (s != null) { return new PlayStatusMsg(s); } } if (HEOS_COMMAND_MODE.equals(command)) { final RepeatStatus r = (RepeatStatus) searchDcpParameter(tokens.get("repeat"), RepeatStatus.values()); final ShuffleStatus s = (ShuffleStatus) searchDcpParameter(tokens.get("shuffle"), ShuffleStatus.values()); if (r != null && s != null) { return new PlayStatusMsg(r, s); } } if (HEOS_EVENT_REPEAT.equals(command)) { final RepeatStatus r = (RepeatStatus) searchDcpParameter(tokens.get("repeat"), RepeatStatus.values()); if (r != null) { return new PlayStatusMsg(r); } } if (HEOS_EVENT_SHUFFLE.equals(command)) { final ShuffleStatus s = (ShuffleStatus) searchDcpParameter(tokens.get("shuffle"), ShuffleStatus.values()); if (s != null) { return new PlayStatusMsg(s); } } } return null; } @Nullable @Override public String buildDcpMsg(boolean isQuery) { if (isQuery) { return "heos://" + HEOS_COMMAND_STATE + "?pid=" + DCP_HEOS_PID + DCP_MSG_SEP + "heos://" + HEOS_COMMAND_MODE + "?pid=" + DCP_HEOS_PID; } return null; } }
9,389
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
TimeInfoMsg.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/messages/TimeInfoMsg.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.messages; import android.annotation.SuppressLint; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import com.mkulesh.onpc.utils.Utils; import java.util.Map; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /* * NET/USB Time Info */ public class TimeInfoMsg extends ISCPMessage { public final static String CODE = "NTM"; public final static String INVALID_TIME = "--:--:--"; /* * (Elapsed time/Track Time Max 99:59:59. If time is unknown, this response is --:--) */ private final String currentTime; private final String maxTime; TimeInfoMsg(EISCPMessage raw) throws Exception { super(raw); final String[] pars = data.split(PAR_SEP); if (pars.length != 2) { throw new Exception("Can not find parameter split character in message " + raw); } currentTime = pars[0]; maxTime = pars[1]; } TimeInfoMsg(String currentTime, String maxTime) { super(0, null); this.currentTime = currentTime; this.maxTime = maxTime; } public String getCurrentTime() { return (currentTime == null || currentTime.isEmpty()) ? INVALID_TIME : currentTime; } public String getMaxTime() { return (maxTime == null || maxTime.isEmpty()) ? INVALID_TIME : maxTime; } @NonNull @Override public String toString() { return CODE + "[" + currentTime + "; " + maxTime + "]"; } /* * Denon control protocol * - Player Now Playing Progress * { * "heos": { * "command": " event/player_now_playing_progress", * "message": "pid=player_id&cur_pos=position_ms&duration=duration_ms" * } * } */ private final static String HEOS_COMMAND = "event/player_now_playing_progress"; @Nullable @SuppressLint("SimpleDateFormat") public static TimeInfoMsg processHeosMessage(@NonNull final String command, @NonNull final Map<String, String> tokens) { if (HEOS_COMMAND.equals(command)) { final String curPosStr = tokens.get("cur_pos"); final String durationStr = tokens.get("duration"); if (curPosStr != null && durationStr != null) { return new TimeInfoMsg( Utils.millisToTime(Integer.parseInt(curPosStr)), Utils.millisToTime(Integer.parseInt(durationStr))); } } return null; } }
3,250
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
RequestListeningMode.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/scripts/RequestListeningMode.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.scripts; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import com.mkulesh.onpc.iscp.MessageChannel; import com.mkulesh.onpc.iscp.State; import com.mkulesh.onpc.iscp.messages.ListeningModeMsg; import com.mkulesh.onpc.utils.Logging; import java.util.Timer; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.atomic.AtomicInteger; import androidx.annotation.NonNull; /* * For some models, it does seem that the listening mode is enabled some * seconds after power on - as though it's got things to initialize before * turning on the audio circuits. The initialization time is unknown. * The solution is to periodically send a constant number of requests * (for example 5 requests) with time interval 1 second until listening * mode still be unknown. */ public class RequestListeningMode implements MessageScriptIf { private static final long LISTENING_MODE_DELAY = 1000; private static final int MAX_LISTENING_MODE_REQUESTS = 5; private final AtomicInteger listeningModeRequests = new AtomicInteger(); private final BlockingQueue<Timer> listeningModeQueue = new ArrayBlockingQueue<>(1, true); @Override public boolean isValid() { return true; } @Override public void initialize(@NonNull final String data) { // nothing to do } @Override public void start(@NonNull State state, @NonNull MessageChannel channel) { Logging.info(this, "started script"); listeningModeRequests.set(0); } @Override public void processMessage(@NonNull ISCPMessage msg, @NonNull State state, @NonNull MessageChannel channel) { if (msg instanceof ListeningModeMsg && ((ListeningModeMsg) msg).getMode() == ListeningModeMsg.Mode.MODE_FF && listeningModeRequests.get() < MAX_LISTENING_MODE_REQUESTS && listeningModeQueue.isEmpty()) { Logging.info(this, "scheduling listening mode request in " + LISTENING_MODE_DELAY + "ms"); final Timer t = new Timer(); listeningModeQueue.add(t); t.schedule(new java.util.TimerTask() { @Override public void run() { listeningModeQueue.poll(); Logging.info(RequestListeningMode.this, "re-requesting LM state [" + listeningModeRequests.addAndGet(1) + "]..."); channel.sendMessage(new EISCPMessage(ListeningModeMsg.CODE, EISCPMessage.QUERY)); } }, LISTENING_MODE_DELAY); } } }
3,408
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
MessageScript.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/scripts/MessageScript.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.scripts; import android.content.Context; import com.mkulesh.onpc.iscp.ConnectionIf; import com.mkulesh.onpc.iscp.EISCPMessage; import com.mkulesh.onpc.iscp.ISCPMessage; import com.mkulesh.onpc.iscp.MessageChannel; import com.mkulesh.onpc.iscp.State; import com.mkulesh.onpc.iscp.messages.InputSelectorMsg; import com.mkulesh.onpc.iscp.messages.ListTitleInfoMsg; import com.mkulesh.onpc.iscp.messages.NetworkServiceMsg; import com.mkulesh.onpc.iscp.messages.OperationCommandMsg; import com.mkulesh.onpc.iscp.messages.PowerStatusMsg; import com.mkulesh.onpc.iscp.messages.ReceiverInformationMsg; import com.mkulesh.onpc.iscp.messages.ServiceType; import com.mkulesh.onpc.iscp.messages.XmlListInfoMsg; import com.mkulesh.onpc.iscp.messages.XmlListItemMsg; import com.mkulesh.onpc.utils.Utils; import org.w3c.dom.Element; import org.w3c.dom.Node; import java.util.ArrayList; import java.util.List; import java.util.Timer; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import static com.mkulesh.onpc.utils.Logging.info; public class MessageScript implements ConnectionIf, MessageScriptIf { enum ActionState { UNSENT, // the command is not yet sent WAITING, // the command has been sent and is waiting for an ack message or time-based wait DONE // the command has completed } private final static String[] ACTION_STATES = new String[]{ "UNSENT", "WAITING", "DONE" }; static class Action { // command to be sent final String cmd; // parameter used for actions command. Empty string means no parameter is used. final String par; // Delay in milliseconds used for action WAIT. Zero means no delay. final int milliseconds; // the command to wait for. Null if time based (or no) wait is used final String wait; // string that must match the acknowledgement message final String resp; // string that must appear as a media list item in an NLA message final String listitem; // The attribute that holds the actual state of this action ActionState state = ActionState.UNSENT; Action(String cmd, String par, final int milliseconds, String wait, String resp, String listitem) { this.cmd = cmd; this.par = par; this.milliseconds = milliseconds; this.wait = wait; this.resp = resp; this.listitem = listitem; } @NonNull public String toString() { return "Action" + "[" + cmd + "," + par + "," + wait + "," + resp + "," + listitem + "]/" + ACTION_STATES[state.ordinal()]; } } // optional connected host (ConnectionIf) private String host = ConnectionIf.EMPTY_HOST; private int port = ConnectionIf.EMPTY_PORT; // optional target zone private int zone = ReceiverInformationMsg.DEFAULT_ACTIVE_ZONE; // optional target tab public String tab = null; // Actions to be performed private final List<Action> actions = new ArrayList<>(); private final Context context; public MessageScript(Context context, @NonNull final String data) { this.context = context; initialize(data); } @Override public boolean isValid() { return !actions.isEmpty(); } @NonNull private String unEscape(@NonNull String str) { str = str.replace("~lt~", "<"); str = str.replace("~gt~", ">"); str = str.replace("~dq~", "\""); return str; } @Override public void initialize(@NonNull final String data) { Utils.openXml(this, data, (final Element elem) -> { if (elem.getTagName().equals("onpcScript")) { if (elem.getAttribute("host") != null) { host = elem.getAttribute("host"); } port = Utils.parseIntAttribute(elem, "port", ConnectionIf.EMPTY_PORT); zone = Utils.parseIntAttribute(elem, "zone", ReceiverInformationMsg.DEFAULT_ACTIVE_ZONE); if (elem.getAttribute("tab") != null) { tab = elem.getAttribute("tab"); } } for (Node prop = elem.getFirstChild(); prop != null; prop = prop.getNextSibling()) { if (prop instanceof Element) { final Element action = (Element) prop; if (action.getTagName().equals("send")) { final String cmd = action.getAttribute("cmd"); if (cmd == null) { throw new Exception("missing command code in 'send' command"); } String par = action.getAttribute("par"); if (par == null) { throw new Exception("missing command parameter in 'send' command"); } par = unEscape(par); final int milliseconds = Utils.parseIntAttribute(action, "wait", -1); final String wait = action.getAttribute("wait"); final String resp = unEscape(action.getAttribute("resp")); final String listitem = unEscape(action.getAttribute("listitem")); if (milliseconds < 0 && (wait == null || wait.isEmpty())) { throw new Exception("missing time or wait CMD in 'send' command"); } actions.add(new Action(cmd, par, milliseconds, wait, resp, listitem)); } } } }); for (Action a : actions) { info(this, a.toString()); } } @Override public void start(@NonNull final State state, @NonNull MessageChannel channel) { // Startup handling. info(this, "started script"); processNextActions(state, channel); } /** * The method implements message handling with respect to the "command"-"wait" logic: * - in "actions" list, search the first non-performed action * - if this action as a "wait" command that waits on a specific message (and * optional parameter), check whether this condition is fulfilled. If yes, set the * action as done and perform the next action * - if the action to be performed is a "cmd" command, send the message (for example * see method AutoPower.processMessage) * - if the action to be performed is a "wait" command with given time (in milliseconds), * set the state to "processing" and start the timer, where the timer body is the * code that shall perform the next message **/ @Override public void processMessage(@NonNull ISCPMessage msg, @NonNull final State state, @NonNull MessageChannel channel) { for (Action a : actions) { if (a.state == ActionState.DONE) { continue; } if (a.state == ActionState.WAITING && a.wait != null) { String log = a + ": compare with message " + msg; if (isResponseMatched(state, a, msg.getCode(), msg.getData())) { info(this, log + " -> response matched"); a.state = ActionState.DONE; processNextActions(state, channel); return; } if (state.serviceType == ServiceType.TUNEIN_RADIO && a.wait.equals(XmlListInfoMsg.CODE) && !a.listitem.isEmpty() && msg.getCode().equals(ListTitleInfoMsg.CODE) && state.isPlaybackMode()) { // Upon change to some services like TuneIn, the receiver may automatically // start the latest playback and no XmlListItemMsg will be received. In this case, // we shall stop playback and resent the service selection command info(this, log + " -> waiting media item, but playing active -> change to list"); final OperationCommandMsg cmd = new OperationCommandMsg(OperationCommandMsg.Command.STOP); channel.sendMessage(cmd.getCmdMsg()); channel.sendMessage(new EISCPMessage(a.cmd, a.par)); } info(this, log + " -> continue waiting"); return; } else { info(this, "Something's wrong, didn't expect to be here"); } } } private void processNextActions(@NonNull final State state, @NonNull MessageChannel channel) { if (!channel.isActive()) { info(this, "message channel stopped"); return; } ActionState aState = ActionState.DONE; for (Action a : actions) { if (a.state != ActionState.DONE) { aState = processAction(state, a, channel); if (aState != ActionState.DONE) { break; } } } if (aState == ActionState.DONE) { info(this, "all commands send"); } } private boolean isStateSet(@NonNull final State state, @NonNull final String cmd, @NonNull final String par) { switch (cmd) { case OperationCommandMsg.CODE: return par.equals(OperationCommandMsg.Command.TOP.toString()) && state.isTopLayer(); case PowerStatusMsg.CODE: return par.equals(state.powerStatus.getCode()); case InputSelectorMsg.CODE: return par.equals(state.inputType.getCode()); case NetworkServiceMsg.CODE: return par.equals(state.serviceType.getCode() + "0"); default: return false; } } private boolean isResponseMatched(@NonNull final State state, @NonNull Action a, @NonNull final String cmd, @Nullable final String par) { if (a.wait.equals(cmd)) { if (!a.listitem.isEmpty()) { final List<XmlListItemMsg> mediaItems = state.cloneMediaItems(); for (XmlListItemMsg item : mediaItems) { if (item.getTitle().equals(a.listitem)) { return true; } } final List<NetworkServiceMsg> serviceItems = state.cloneServiceItems(); for (NetworkServiceMsg item : serviceItems) { if (context.getString(item.getService().getDescriptionId()).equals(a.listitem)) { return true; } } } else return par != null && (a.resp.isEmpty() || a.resp.equals(par)); } return false; } private ActionState processAction(@NonNull final State state, @NonNull final Action a, @NonNull MessageChannel channel) { if (isStateSet(state, a.cmd, a.par)) { boolean isMatched = (!a.resp.isEmpty() && isStateSet(state, a.wait, a.resp)) || isResponseMatched(state, a, a.wait, null); a.state = isMatched ? ActionState.DONE : ActionState.WAITING; info(this, a + ": the required state is already set, no need to send action message"); if (a.state == ActionState.DONE) { return a.state; } } else if (a.cmd.equals("NA") && a.par.equals("NA")) { info(this, a + ": no action message to send"); } else { EISCPMessage msg = null; if (a.cmd.equals(XmlListInfoMsg.CODE)) { final List<XmlListItemMsg> cloneMediaItems = state.cloneMediaItems(); for (XmlListItemMsg item : cloneMediaItems) { if (item.getTitle().equals(a.par)) { msg = item.getCmdMsg(); } } } if (msg == null) { msg = new EISCPMessage(a.cmd, a.par); } channel.sendMessage(msg); info(this, a + ": sent message " + msg); } a.state = ActionState.WAITING; if (a.milliseconds >= 0) { info(this, a + ": scheduling timer for " + a.milliseconds + " milliseconds"); final Timer t = new Timer(); t.schedule(new java.util.TimerTask() { @Override public void run() { info(MessageScript.this, a + ": timer expired"); a.state = ActionState.DONE; processNextActions(state, channel); } }, a.milliseconds); } return a.state; } @NonNull @Override public String getHost() { return host; } @Override public int getPort() { return port; } @NonNull @Override public String getHostAndPort() { return Utils.ipToString(host, port); } public int getZone() { return zone; } }
14,423
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
AutoPower.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/scripts/AutoPower.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.scripts; import com.mkulesh.onpc.iscp.ISCPMessage; import com.mkulesh.onpc.iscp.MessageChannel; import com.mkulesh.onpc.iscp.State; import com.mkulesh.onpc.iscp.messages.PowerStatusMsg; import com.mkulesh.onpc.iscp.messages.ReceiverInformationMsg; import com.mkulesh.onpc.utils.Logging; import androidx.annotation.NonNull; /** * The class performs receiver auto-power on startup **/ public class AutoPower implements MessageScriptIf { public enum AutoPowerMode { POWER_ON, ALL_STANDBY } enum AllStandbyStep { NONE, ALL_STB_SEND, STB_SEND } private final AutoPowerMode autoPowerMode; private boolean done = false; AllStandbyStep allStandbyStep = AllStandbyStep.NONE; public AutoPower(final AutoPowerMode autoPowerMode) { this.autoPowerMode = autoPowerMode; } @Override public boolean isValid() { return true; } @Override public void initialize(@NonNull final String data) { // nothing to do } @Override public void start(@NonNull final State state, @NonNull MessageChannel channel) { Logging.info(this, "started script: " + autoPowerMode); done = false; allStandbyStep = AllStandbyStep.NONE; } @Override public void processMessage(@NonNull ISCPMessage msg, @NonNull final State state, @NonNull MessageChannel channel) { // Auto power-on once at first PowerStatusMsg if (msg instanceof PowerStatusMsg && !done) { final PowerStatusMsg pwrMsg = (PowerStatusMsg) msg; if (autoPowerMode == AutoPowerMode.POWER_ON && !state.isOn()) { Logging.info(this, "request auto-power on startup"); final PowerStatusMsg cmd = new PowerStatusMsg(state.getActiveZone(), PowerStatusMsg.PowerStatus.ON); channel.sendMessage(cmd.getCmdMsg()); done = true; } else if (autoPowerMode == AutoPowerMode.ALL_STANDBY) { switch (allStandbyStep) { case NONE: { Logging.info(this, "request all-standby on startup"); final PowerStatusMsg cmd = new PowerStatusMsg( ReceiverInformationMsg.DEFAULT_ACTIVE_ZONE, PowerStatusMsg.PowerStatus.ALL_STB); channel.sendMessage(cmd.getCmdMsg()); allStandbyStep = AllStandbyStep.ALL_STB_SEND; break; } case ALL_STB_SEND: { if (pwrMsg.getPowerStatus() == PowerStatusMsg.PowerStatus.STB || pwrMsg.getPowerStatus() == PowerStatusMsg.PowerStatus.ALL_STB) { done = true; } else { Logging.info(this, "request standby on startup"); final PowerStatusMsg cmd = new PowerStatusMsg( ReceiverInformationMsg.DEFAULT_ACTIVE_ZONE, PowerStatusMsg.PowerStatus.STB); channel.sendMessage(cmd.getCmdMsg()); allStandbyStep = AllStandbyStep.STB_SEND; } break; } case STB_SEND: done = true; break; } if (done) { Logging.info(this, "close app after all-standby on startup"); System.exit(0); } } } } }
4,408
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
MessageScriptIf.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/scripts/MessageScriptIf.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp.scripts; import com.mkulesh.onpc.iscp.ISCPMessage; import com.mkulesh.onpc.iscp.MessageChannel; import com.mkulesh.onpc.iscp.State; import androidx.annotation.NonNull; public interface MessageScriptIf { /** * Checks whether the script contains valid action to be performed **/ boolean isValid(); /** * This method shall parse the data field in the input intent. After XML is parsed, * the method fills attributes host, port, and zone, if the input XML contains this * information. After it, the method fills a list of available action. This list contains * elements of type "Action" that is defined within this class. If the list of actions is * not empty, the MessageScript is valid and these actions will be performed after the * connection is established. **/ void initialize(@NonNull final String data); /** * This method is called from the state manager after the connection is established * Before the method is called, the state manager checks whether this class contains * valid actions; i.e method is not called for invalid script **/ void start(@NonNull final State state, @NonNull MessageChannel channel); /** * This method is called from the state manager after the input message is processed. * Before the method is called, the state manager checks whether this class contains * valid actions; i.e method is not called for invalid script **/ void processMessage(@NonNull ISCPMessage msg, @NonNull final State state, @NonNull MessageChannel channel); }
2,290
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
AppTask.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/utils/AppTask.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.utils; import java.util.concurrent.atomic.AtomicBoolean; public class AppTask { private final AtomicBoolean active = new AtomicBoolean(); protected AppTask(boolean a) { active.set(a); } public void start() { synchronized (active) { active.set(true); } } public void stop() { synchronized (active) { active.set(false); } } public boolean isActive() { synchronized (active) { return active.get(); } } }
1,273
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
Logging.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/utils/Logging.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.utils; import android.annotation.SuppressLint; import android.util.Log; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.atomic.AtomicInteger; @SuppressWarnings("SameReturnValue") public final class Logging { public static boolean saveLogging = false; private final static int LOG_SIZE = 5000; private final static BlockingQueue<String> latestLogging = new ArrayBlockingQueue<>(LOG_SIZE, true); private final static AtomicInteger logLineNumber = new AtomicInteger(0); public static boolean isEnabled() { // Should be false in release build return true; } public static boolean isTimeMsgEnabled() { // Should be false in release build return false; } @SuppressLint("DefaultLocale") public static void info(Object o, String text) { if (isEnabled()) { final String out = o.getClass().getSimpleName() + ": " + text; if (saveLogging) { try { if (latestLogging.size() >= LOG_SIZE - 1) { latestLogging.take(); } final int l = logLineNumber.addAndGet(1); //noinspection ResultOfMethodCallIgnored latestLogging.offer(String.format("#%04d: ", l) + out); } catch (Exception e) { // nothing to do } } Log.d("onpc", out); } } public static String getLatestLogging() { final StringBuilder str = new StringBuilder(); try { while (!latestLogging.isEmpty()) { str.append(latestLogging.take()).append("\n"); } } catch (Exception e) { str.append("Can not collect logging: ").append(e.getLocalizedMessage()); } return str.toString(); } }
2,766
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
Utils.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/utils/Utils.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.utils; import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Configuration; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.EISCPMessage; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.nio.charset.Charset; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.List; import java.util.zip.GZIPInputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import androidx.annotation.AttrRes; import androidx.annotation.ColorInt; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.AppCompatButton; import androidx.appcompat.widget.AppCompatImageButton; import androidx.drawerlayout.widget.DrawerLayout; public class Utils { @SuppressWarnings("CharsetObjectCanBeUsed") public static final Charset UTF_8 = Charset.forName("UTF-8"); public static byte[] catBuffer(byte[] bytes, int offset, int length) { final byte[] newBytes = new byte[length]; System.arraycopy(bytes, offset, newBytes, 0, length); return newBytes; } @SuppressWarnings("deprecation") @SuppressLint("NewApi") public static Drawable getDrawable(Context context, int icon) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return context.getResources().getDrawable(icon, context.getTheme()); } else { return context.getResources().getDrawable(icon); } } public static byte[] streamToByteArray(InputStream stream) throws IOException { byte[] buffer = new byte[1024]; ByteArrayOutputStream os = new ByteArrayOutputStream(); int line; // read bytes from stream, and store them in buffer while ((line = stream.read(buffer)) != -1) { // Writes bytes from byte array (buffer) into output stream. os.write(buffer, 0, line); } os.flush(); os.close(); stream.close(); return os.toByteArray(); } /** * XML utils */ public interface XmlProcessor { void onXmlOpened(final Element elem) throws Exception; } public static void openXml(Object owner, @NonNull final String data, XmlProcessor processor) { try { InputStream stream = new ByteArrayInputStream(data.getBytes(UTF_8)); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet factory.setExpandEntityReferences(false); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.parse(stream); final Node object = doc.getDocumentElement(); //noinspection ConstantConditions if (object instanceof Element) { //noinspection CastCanBeRemovedNarrowingVariableType processor.onXmlOpened((Element) object); } } catch (Exception e) { Logging.info(owner, "Failed to parse XML: " + e.getLocalizedMessage()); } } public static boolean ensureAttribute(Element e, String type, String s) { return e.getAttribute(type) != null && e.getAttribute(type).equals(s); } public static Element getElement(final Document doc, final String name) { for (Node object = doc.getDocumentElement(); object != null; object = object.getNextSibling()) { if (object instanceof Element) { final Element popup = (Element) object; if (popup.getTagName().equals(name)) { return popup; } } } return null; } public static List<Element> getElements(final Element e, final String name) { List<Element> retValue = new ArrayList<>(); for (Node object = e.getFirstChild(); object != null; object = object.getNextSibling()) { if (object instanceof Element) { final Element en = (Element) object; if (name == null || name.equals(en.getTagName())) { retValue.add(en); } } } return retValue; } public static int parseIntAttribute(@NonNull final Element e, @NonNull final String name, int defValue) { final String val = e.getAttribute(name); if (val != null) { try { return Integer.parseInt(e.getAttribute(name)); } catch (NumberFormatException ex) { return defValue; } } return defValue; } @Nullable public static String getFirstElementValue(@NonNull Element element, @NonNull String tag, @Nullable String defValue) { for (Node node = element.getFirstChild(); node != null; node = node.getNextSibling()) { if (node instanceof Element) { final Element en = (Element) node; if (tag.equalsIgnoreCase(en.getTagName())) { return en.getChildNodes().item(0).getNodeValue(); } } } return defValue; } /** * Procedure returns theme color */ @ColorInt public static int getThemeColorAttr(final Context context, @AttrRes int resId) { final TypedValue value = new TypedValue(); context.getTheme().resolveAttribute(resId, value, true); return value.data; } /** * Procedure updates menu item color depends its enabled state */ public static void updateMenuIconColor(Context context, MenuItem m) { setDrawableColorAttr(context, m.getIcon(), m.isEnabled() ? android.R.attr.textColorTertiary : R.attr.colorPrimaryDark); } /** * Procedure sets AppCompatImageButton color given by attribute ID */ public static void setImageButtonColorAttr(Context context, AppCompatImageButton b, @AttrRes int resId) { final int c = getThemeColorAttr(context, resId); b.clearColorFilter(); b.setColorFilter(c, PorterDuff.Mode.SRC_ATOP); } public static void setButtonEnabled(Context context, View b, boolean isEnabled) { @AttrRes int resId = isEnabled ? R.attr.colorButtonEnabled : R.attr.colorButtonDisabled; b.setEnabled(isEnabled); if (b instanceof AppCompatImageButton) { Utils.setImageButtonColorAttr(context, (AppCompatImageButton) b, resId); } if (b instanceof AppCompatButton) { ((AppCompatButton) b).setTextColor(Utils.getThemeColorAttr(context, resId)); } } public static void setButtonSelected(Context context, View b, boolean isSelected) { @AttrRes int resId = isSelected ? R.attr.colorAccent : R.attr.colorButtonEnabled; b.setSelected(isSelected); if (b instanceof AppCompatImageButton) { Utils.setImageButtonColorAttr(context, (AppCompatImageButton) b, resId); } if (b instanceof AppCompatButton) { ((AppCompatButton) b).setTextColor(Utils.getThemeColorAttr(context, resId)); } } /** * Procedure sets ImageView background color given by attribute ID */ public static void setImageViewColorAttr(Context context, ImageView b, @AttrRes int resId) { final int c = getThemeColorAttr(context, resId); b.clearColorFilter(); b.setColorFilter(c, PorterDuff.Mode.SRC_ATOP); } public static void setDrawableColorAttr(Context c, Drawable drawable, @AttrRes int resId) { if (drawable != null) { drawable.clearColorFilter(); drawable.setColorFilter(getThemeColorAttr(c, resId), PorterDuff.Mode.SRC_ATOP); } } /** * Fix dialog icon color after dialog creation. Necessary for older Android Versions */ public static void fixDialogLayout(@NonNull AlertDialog dialog, @Nullable @AttrRes Integer resId) { final int width = (int)(dialog.getContext().getResources().getDisplayMetrics().widthPixels * 0.95); final int height = (int)(dialog.getContext().getResources().getDisplayMetrics().heightPixels * 0.95); if (dialog.getWindow() != null) { dialog.getWindow().setLayout(Math.min(width, height), ViewGroup.LayoutParams.WRAP_CONTENT); } final ImageView imageView = dialog.findViewById(android.R.id.icon); if (resId != null && imageView != null) { Utils.setImageViewColorAttr(dialog.getContext(), imageView, resId); } } /** * Procedure hows toast that contains description of the given button */ @SuppressLint("RtlHardcoded") public static boolean showButtonDescription(Context context, View button) { final CharSequence contentDesc = button.getContentDescription(); final ViewGroup dummyView = null; //noinspection ConstantConditions final LinearLayout toastView = (LinearLayout) LayoutInflater.from(context). inflate(R.layout.widget_toast, dummyView, false); final TextView textView = toastView != null ? toastView.findViewById(R.id.toast_message) : null; if (contentDesc != null && contentDesc.length() > 0 && textView != null) { textView.setText(contentDesc); int[] pos = new int[2]; button.getLocationOnScreen(pos); final Toast t = new Toast(context); t.setView(toastView); t.setDuration(Toast.LENGTH_SHORT); t.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0); toastView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); final int x = pos[0] + button.getMeasuredWidth() / 2 - (toastView.getMeasuredWidth() / 2); final int y = pos[1] - 2 * toastView.getMeasuredHeight() - context.getResources().getDimensionPixelSize(R.dimen.activity_vertical_margin_port); t.setGravity(Gravity.TOP | Gravity.LEFT, x, y); t.show(); return true; } return false; } @SuppressWarnings("deprecation") public static boolean isToastVisible(Toast toast) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { return toast != null; } else { return toast != null && toast.getView() != null && toast.getView().isShown(); } } public static int timeToSeconds(final String timestampStr) { try { // #88: Track time seek is frozen on NT-503 // some players like NT-503 use format MM:SS // instead of HH:MM:SS String[] tokens = timestampStr.split(":"); if (tokens.length == 3) { int hours = Integer.parseInt(tokens[0]); int minutes = Integer.parseInt(tokens[1]); int seconds = Integer.parseInt(tokens[2]); return 3600 * hours + 60 * minutes + seconds; } else { int minutes = Integer.parseInt(tokens[0]); int seconds = Integer.parseInt(tokens[1]); return 60 * minutes + seconds; } } catch (Exception ex) { return -1; } } @SuppressLint("DefaultLocale") public static String millisToTime(int millis) { final int inpSec = millis / 1000; final int hours = inpSec / 3600; final int minutes = (inpSec - hours * 3600) / 60; final int seconds = inpSec - hours * 3600 - minutes * 60; return String.format("%02d:%02d:%02d", hours, minutes, seconds); } /** * Procedure checks whether the hard keyboard is available */ private static boolean isHardwareKeyboardAvailable(Context context) { return context.getResources().getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS; } public static void showSoftKeyboard(Context context, View v, boolean flag) { if (Utils.isHardwareKeyboardAvailable(context)) { return; } final InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); if (imm == null) { return; } if (flag) { imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY); } else { imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } } /** * Procedure creates new dot-separated DecimalFormat */ public static DecimalFormat getDecimalFormat(String format) { DecimalFormat df = new DecimalFormat(format); DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setDecimalSeparator('.'); dfs.setExponentSeparator("e"); df.setDecimalFormatSymbols(dfs); return df; } @SuppressWarnings("deprecation") public static void setDrawerListener(DrawerLayout mDrawerLayout, ActionBarDrawerToggle mDrawerToggle) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { mDrawerLayout.removeDrawerListener(mDrawerToggle); mDrawerLayout.addDrawerListener(mDrawerToggle); } else { mDrawerLayout.setDrawerListener(mDrawerToggle); } } public static String intToneToString(Character m, int tone) { if (tone == 0) { return String.format("%c%02x", m, tone); } final Character s = tone < 0 ? '-' : '+'; return String.format("%c%c%1x", m, s, Math.abs(tone)).toUpperCase(); } public static String intLevelToString(int tone, int cmdLength) { if (tone == 0) { return cmdLength == 2 ? "00" : "000"; } else { final Character s = tone < 0 ? '-' : '+'; final String format = cmdLength == 2 ? "%c%1x" : "%c%02x"; return String.format(format, s, Math.abs(tone)).toUpperCase(); } } @NonNull public static String ipToString(String host, String port) { return host + ":" + port; } @NonNull public static String ipToString(String host, int port) { return host + ":" + port; } @NonNull public static String getStringPref(@NonNull final SharedPreferences preferences, @NonNull final String par, @NonNull final String def) { final String val = preferences.getString(par, def); //noinspection ConstantConditions return val == null ? def : val; } public static boolean isInteger(final String text) { try { Integer.parseInt(text); return true; } catch (NumberFormatException nfe) { return false; } } public static byte[] getUrlData(URL url, boolean info) { try { if (info) { Logging.info(url, "loading data from URL: " + url.toString()); } URLConnection urlConnection = url.openConnection(); urlConnection.setRequestProperty("Accept-Encoding", "gzip"); InputStream inputStream; if ("gzip".equals(urlConnection.getContentEncoding())) { inputStream = new GZIPInputStream(urlConnection.getInputStream()); } else { inputStream = urlConnection.getInputStream(); } return streamToByteArray(inputStream); } catch (Exception e) { Logging.info(url, "can not open URL: " + e.getLocalizedMessage()); return null; } } public static int getUrlHeaderLength(byte[] buffer) { int length = 0; while (true) { String str = new String(buffer, length, buffer.length - length, UTF_8); final int lf = str.indexOf(EISCPMessage.LF); if (str.startsWith("Content-") && lf > 0) { length += lf; while (buffer[length] == EISCPMessage.LF || buffer[length] == EISCPMessage.CR) { length++; } continue; } break; } return length; } }
18,581
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
DeviceFragment.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/fragments/DeviceFragment.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.fragments; import android.os.Build; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import com.mkulesh.onpc.R; import com.mkulesh.onpc.config.CfgAppSettings; import com.mkulesh.onpc.iscp.ConnectionIf; import com.mkulesh.onpc.iscp.ISCPMessage; import com.mkulesh.onpc.iscp.State; import com.mkulesh.onpc.iscp.messages.AutoPowerMsg; import com.mkulesh.onpc.iscp.messages.DcpAudioRestorerMsg; import com.mkulesh.onpc.iscp.messages.DcpEcoModeMsg; import com.mkulesh.onpc.iscp.messages.DigitalFilterMsg; import com.mkulesh.onpc.iscp.messages.DimmerLevelMsg; import com.mkulesh.onpc.iscp.messages.FirmwareUpdateMsg; import com.mkulesh.onpc.iscp.messages.FriendlyNameMsg; import com.mkulesh.onpc.iscp.messages.GoogleCastAnalyticsMsg; import com.mkulesh.onpc.iscp.messages.HdmiCecMsg; import com.mkulesh.onpc.iscp.messages.LateNightCommandMsg; import com.mkulesh.onpc.iscp.messages.MusicOptimizerMsg; import com.mkulesh.onpc.iscp.messages.NetworkStandByMsg; import com.mkulesh.onpc.iscp.messages.PhaseMatchingBassMsg; import com.mkulesh.onpc.iscp.messages.SleepSetCommandMsg; import com.mkulesh.onpc.iscp.messages.SpeakerACommandMsg; import com.mkulesh.onpc.iscp.messages.SpeakerBCommandMsg; import com.mkulesh.onpc.utils.Logging; import java.util.HashSet; import androidx.annotation.IdRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import androidx.appcompat.widget.AppCompatImageButton; public class DeviceFragment extends BaseFragment { private enum SpeakerABStatus { NONE(R.string.device_two_way_switch_none, SpeakerACommandMsg.Status.NONE, SpeakerBCommandMsg.Status.NONE), OFF(R.string.speaker_ab_command_ab_off, SpeakerACommandMsg.Status.OFF, SpeakerBCommandMsg.Status.OFF), ON(R.string.speaker_ab_command_ab_on, SpeakerACommandMsg.Status.ON, SpeakerBCommandMsg.Status.ON), A_ONLY(R.string.speaker_ab_command_a_only, SpeakerACommandMsg.Status.ON, null), B_ONLY(R.string.speaker_ab_command_b_only, null, SpeakerBCommandMsg.Status.ON); @StringRes final int descriptionId; final SpeakerACommandMsg.Status speakerA; final SpeakerBCommandMsg.Status speakerB; SpeakerABStatus(@StringRes final int descriptionId, final SpeakerACommandMsg.Status speakerA, final SpeakerBCommandMsg.Status speakerB) { this.descriptionId = descriptionId; this.speakerA = speakerA; this.speakerB = speakerB; } @StringRes int getDescriptionId() { return descriptionId; } } private EditText friendlyName = null; public DeviceFragment() { // Empty constructor required for fragment subclasses } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { initializeFragment(inflater, container, R.layout.device_fragment, CfgAppSettings.Tabs.DEVICE); // Friendly name { friendlyName = rootView.findViewById(R.id.device_edit_friendly_name); final AppCompatImageButton b = rootView.findViewById(R.id.device_change_friendly_name); prepareButtonListeners(b, null, () -> { if (activity.isConnected()) { activity.getStateManager().sendMessage( new FriendlyNameMsg(friendlyName.getText().toString())); // #119: Improve clearing focus for friendly name edit field friendlyName.clearFocus(); } }); setButtonEnabled(b, true); // #119: Improve clearing focus for friendly name edit field // OnClick for background layout: clear focus for friendly name text field { LinearLayout l = rootView.findViewById(R.id.device_background_layout); l.setClickable(true); l.setEnabled(true); l.setOnClickListener((v) -> friendlyName.clearFocus()); } } prepareImageButton(R.id.btn_firmware_update, null); prepareImageButton(R.id.device_dimmer_level_toggle, new DimmerLevelMsg(DimmerLevelMsg.Level.TOGGLE)); prepareImageButton(R.id.device_digital_filter_toggle, new DigitalFilterMsg(DigitalFilterMsg.Filter.TOGGLE)); prepareImageButton(R.id.music_optimizer_toggle, new MusicOptimizerMsg(MusicOptimizerMsg.Status.TOGGLE)); prepareImageButton(R.id.device_auto_power_toggle, new AutoPowerMsg(AutoPowerMsg.Status.TOGGLE)); prepareImageButton(R.id.hdmi_cec_toggle, null); prepareImageButton(R.id.phase_matching_bass_toggle, new PhaseMatchingBassMsg(PhaseMatchingBassMsg.Status.TOGGLE)); prepareImageButton(R.id.sleep_time_toggle, null); prepareImageButton(R.id.speaker_ab_command_toggle, null); prepareImageButton(R.id.google_cast_analytics_toggle, null); prepareImageButton(R.id.late_night_command_toggle, new LateNightCommandMsg(LateNightCommandMsg.Status.UP)); prepareImageButton(R.id.network_standby_toggle, null); prepareImageButton(R.id.dcp_eco_mode_toggle, null); prepareImageButton(R.id.dcp_audio_restorer_toggle, null); updateContent(); return rootView; } @Override public void onResume() { if (friendlyName != null) { friendlyName.clearFocus(); } super.onResume(); } @Override protected void updateStandbyView(@Nullable final State state) { updateDeviceInformation(state); if (state != null) { updateDeviceSettings(state); } else { final int[] settingsLayout = new int[]{ R.id.settings_title, R.id.settings_divider, R.id.device_dimmer_level_layout, R.id.device_digital_filter_layout, R.id.music_optimizer_layout, R.id.device_auto_power_layout, R.id.hdmi_cec_layout, R.id.phase_matching_bass_layout, R.id.sleep_time_layout, R.id.speaker_ab_layout, R.id.google_cast_analytics_layout, R.id.late_night_command_layout, R.id.network_standby_layout, R.id.dcp_eco_mode_layout, R.id.dcp_audio_restorer_layout }; for (int layoutId : settingsLayout) { rootView.findViewById(layoutId).setVisibility(View.GONE); } } } @Override protected void updateActiveView(@NonNull final State state, @NonNull final HashSet<State.ChangeType> eventChanges) { if (eventChanges.contains(State.ChangeType.COMMON) || eventChanges.contains(State.ChangeType.RECEIVER_INFO)) { Logging.info(this, "Updating device properties"); updateDeviceInformation(state); updateDeviceSettings(state); } } private void updateDeviceInformation(@Nullable final State state) { // Host ((TextView) rootView.findViewById(R.id.device_info_address)).setText( (state != null) ? state.getHostAndPort() : ""); // Friendly name final boolean isFnValid = state != null && state.isFriendlyName(); final LinearLayout fnLayout = rootView.findViewById(R.id.device_friendly_name); fnLayout.setVisibility(isFnValid ? View.VISIBLE : View.GONE); if (isFnValid) { // Friendly name friendlyName.setText(state.getDeviceName(true)); } // Receiver information final boolean isRiValid = state != null && state.isReceiverInformation() && !state.deviceProperties.isEmpty(); final LinearLayout riLayout = rootView.findViewById(R.id.device_receiver_information); riLayout.setVisibility(isRiValid ? View.VISIBLE : View.GONE); if (isRiValid) { // Common properties ((TextView) rootView.findViewById(R.id.device_brand)).setText(state.getBrand()); ((TextView) rootView.findViewById(R.id.device_model)).setText(state.getModel()); ((TextView) rootView.findViewById(R.id.device_year)).setText(state.deviceProperties.get("year")); // Firmware version if (state.deviceProperties.get("firmwareversion") != null) { StringBuilder version = new StringBuilder(); version.append(state.deviceProperties.get("firmwareversion")); final boolean isValidVersions = state.firmwareStatus == FirmwareUpdateMsg.Status.ACTUAL || state.firmwareStatus == FirmwareUpdateMsg.Status.NEW_VERSION || state.firmwareStatus == FirmwareUpdateMsg.Status.NEW_VERSION_NORMAL || state.firmwareStatus == FirmwareUpdateMsg.Status.NEW_VERSION_FORCE; final boolean isUpdating = state.firmwareStatus == FirmwareUpdateMsg.Status.UPDATE_STARTED || state.firmwareStatus == FirmwareUpdateMsg.Status.UPDATE_COMPLETE; if (isValidVersions || isUpdating) { version.append(", ").append(getStringValue(state.firmwareStatus.getDescriptionId())); } if (isValidVersions && state.protoType == ConnectionIf.ProtoType.ISCP) { // Update button final AppCompatImageButton b = rootView.findViewById(R.id.btn_firmware_update); b.setVisibility(View.VISIBLE); setButtonEnabled(b, state.isOn()); prepareButtonListeners(b, null, this::onFirmwareUpdateButton); } ((TextView) rootView.findViewById(R.id.device_firmware)).setText(version.toString()); } // Google cast version ((TextView) rootView.findViewById(R.id.google_cast_version)).setText(state.googleCastVersion); } final int[] deviceInfoLayout = new int[]{ R.id.device_info_layout, R.id.device_info_divider }; for (int layoutId : deviceInfoLayout) { rootView.findViewById(layoutId).setVisibility(isFnValid || isRiValid ? View.VISIBLE : View.GONE); } if (state != null) { hidePlatformSpecificParameters(state.protoType); } } private void hidePlatformSpecificParameters(ConnectionIf.ProtoType protoType) { final int vis = protoType == ConnectionIf.ProtoType.ISCP ? View.VISIBLE : View.GONE; ((LinearLayout) (rootView.findViewById(R.id.device_year).getParent())).setVisibility(vis); ((LinearLayout) (rootView.findViewById(R.id.google_cast_version).getParent())).setVisibility(vis); } private void onFirmwareUpdateButton() { if (getContext() != null && activity.isConnected() && activity.getStateManager().getState().isOn()) { final Dialogs dl = new Dialogs(activity); dl.showFirmwareUpdateDialog(); } } private void updateDeviceSettings(@NonNull final State state) { // Update settings rootView.findViewById(R.id.settings_title).setVisibility(View.GONE); rootView.findViewById(R.id.settings_divider).setVisibility(View.GONE); // Dimmer level prepareSettingPanel(state, state.dimmerLevel != DimmerLevelMsg.Level.NONE, R.id.device_dimmer_level_layout, state.dimmerLevel.getDescriptionId(), null); // Digital filter prepareSettingPanel(state, state.digitalFilter != DigitalFilterMsg.Filter.NONE, R.id.device_digital_filter_layout, state.digitalFilter.getDescriptionId(), null); // Music Optimizer prepareSettingPanel(state, state.musicOptimizer != MusicOptimizerMsg.Status.NONE, R.id.music_optimizer_layout, state.musicOptimizer.getDescriptionId(), null); // Auto power prepareSettingPanel(state, state.autoPower != AutoPowerMsg.Status.NONE, R.id.device_auto_power_layout, state.autoPower.getDescriptionId(), null); // HDMI CEC prepareSettingPanel(state, state.hdmiCec != HdmiCecMsg.Status.NONE, R.id.hdmi_cec_layout, state.hdmiCec.getDescriptionId(), new HdmiCecMsg(HdmiCecMsg.toggle(state.hdmiCec, state.protoType))); // Phase Matching Bass Command prepareSettingPanel(state, state.phaseMatchingBass != PhaseMatchingBassMsg.Status.NONE, R.id.phase_matching_bass_layout, state.phaseMatchingBass.getDescriptionId(), null); // Sleep time { final String description = state.sleepTime == SleepSetCommandMsg.SLEEP_OFF ? getStringValue(R.string.device_two_way_switch_off) : state.sleepTime + " " + getStringValue(R.string.device_sleep_time_minutes); prepareSettingPanel(state, state.sleepTime != SleepSetCommandMsg.NOT_APPLICABLE, R.id.sleep_time_layout, description, new SleepSetCommandMsg(SleepSetCommandMsg.toggle(state.sleepTime, state.protoType))); } // Speaker A/B (For Main zone and Zone 2 only) { final int zone = state.getActiveZone(); final boolean zoneAllowed = (zone < 2); final SpeakerABStatus spState = getSpeakerABStatus(state.speakerA, state.speakerB); prepareSettingPanel(state, zoneAllowed && spState != SpeakerABStatus.NONE, R.id.speaker_ab_layout, spState.getDescriptionId(), null); final AppCompatImageButton b = rootView.findViewById(R.id.speaker_ab_command_toggle); // OFF -> A_ONLY -> B_ONLY -> ON -> OFF (optional) -> A_ONLY -> B_ONLY -> ON -> ... switch (spState) { case NONE: // nothing to do break; case OFF: case B_ONLY: prepareButtonListeners(b, new SpeakerACommandMsg(zone, SpeakerACommandMsg.Status.ON), () -> sendQueries(zone)); break; case A_ONLY: prepareButtonListeners(b, new SpeakerBCommandMsg(zone, SpeakerBCommandMsg.Status.ON), () -> { activity.getStateManager().sendMessage( new SpeakerACommandMsg(zone, SpeakerACommandMsg.Status.OFF)); sendQueries(zone); }); break; case ON: if (state.getModel().equals("DTM-6")) { // This feature allowed for DTM-6 only since some Onkyo models go to "Standby" // power mode by accident when both zones are turned off at the same time. prepareButtonListeners(b, new SpeakerBCommandMsg(zone, SpeakerBCommandMsg.Status.OFF), () -> { activity.getStateManager().sendMessage( new SpeakerACommandMsg(zone, SpeakerACommandMsg.Status.OFF)); sendQueries(zone); }); } else { prepareButtonListeners(b, new SpeakerBCommandMsg(zone, SpeakerBCommandMsg.Status.OFF), () -> sendQueries(zone)); } break; } } // Google Cast analytics prepareSettingPanel(state, state.googleCastAnalytics != GoogleCastAnalyticsMsg.Status.NONE, R.id.google_cast_analytics_layout, state.googleCastAnalytics.getDescriptionId(), new GoogleCastAnalyticsMsg(GoogleCastAnalyticsMsg.toggle(state.googleCastAnalytics))); // Late Night Command prepareSettingPanel(state, state.lateNightMode != LateNightCommandMsg.Status.NONE, R.id.late_night_command_layout, state.lateNightMode.getDescriptionId(), null); // Network Standby Command prepareSettingPanel(state, state.networkStandBy != NetworkStandByMsg.Status.NONE, R.id.network_standby_layout, state.networkStandBy.getDescriptionId(), null); { final AppCompatImageButton b = rootView.findViewById(R.id.network_standby_toggle); prepareButtonListeners(b, null, this::onNetworkStandByToggle); } // DCP ECO mode prepareSettingPanel(state, state.dcpEcoMode != DcpEcoModeMsg.Status.NONE, R.id.dcp_eco_mode_layout, state.dcpEcoMode.getDescriptionId(), new DcpEcoModeMsg(DcpEcoModeMsg.toggle(state.dcpEcoMode))); // DCP audio restorer prepareSettingPanel(state, state.dcpAudioRestorer != DcpAudioRestorerMsg.Status.NONE, R.id.dcp_audio_restorer_layout, state.dcpAudioRestorer.getDescriptionId(), new DcpAudioRestorerMsg(DcpAudioRestorerMsg.toggle(state.dcpAudioRestorer))); } private void onNetworkStandByToggle() { if (getContext() == null || !activity.isConnected() || !activity.getStateManager().getState().isOn()) { return; } final NetworkStandByMsg.Status networkStandBy = activity.getStateManager().getState().networkStandBy; if (networkStandBy == NetworkStandByMsg.Status.OFF) { activity.getStateManager().sendMessage(new NetworkStandByMsg(NetworkStandByMsg.Status.ON)); } else { final Dialogs dl = new Dialogs(activity); dl.showNetworkStandByDialog(); } } private void sendQueries(int zone) { final String[] speakerStateQueries = new String[]{ SpeakerACommandMsg.ZONE_COMMANDS[zone], SpeakerBCommandMsg.ZONE_COMMANDS[zone] }; activity.getStateManager().sendQueries(speakerStateQueries, "requesting speaker state..."); } private void prepareSettingPanel(@NonNull final State state, boolean visible, @IdRes int layoutId, @StringRes int descriptionId, final ISCPMessage msg) { prepareSettingPanel(state, visible, layoutId, getStringValue(descriptionId), msg); } private void prepareSettingPanel(@NonNull final State state, boolean visible, @IdRes int layoutId, final String description, final ISCPMessage msg) { final LinearLayout layout = rootView.findViewById(layoutId); if (!visible || !state.isOn()) { layout.setVisibility(View.GONE); return; } rootView.findViewById(R.id.settings_title).setVisibility(View.VISIBLE); rootView.findViewById(R.id.settings_divider).setVisibility(View.VISIBLE); layout.setVisibility(View.VISIBLE); TextView tv = null; AppCompatImageButton button = null; for (int i = 0; i < layout.getChildCount(); i++) { final View child = layout.getChildAt(i); if (child instanceof TextView) { tv = (TextView) child; if (tv.getTag() != null && "VALUE".equals(tv.getTag())) { tv.setText(description); } } if (child instanceof AppCompatImageButton) { if (msg != null) { // In order to avoid scrolling up if device name field is focused, // clear its focus prepareButtonListeners(child, msg, friendlyName::clearFocus); } setButtonEnabled(child, state.isOn()); if (state.isOn()) { button = (AppCompatImageButton) child; } } } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { if (tv != null && button != null) { final AppCompatImageButton b = button; tv.setEnabled(true); tv.setClickable(true); tv.setOnClickListener((View v) -> b.callOnClick()); } } } private void prepareImageButton(@IdRes int buttonId, final ISCPMessage msg) { final AppCompatImageButton b = rootView.findViewById(buttonId); prepareButtonListeners(b, msg, friendlyName::clearFocus); setButtonEnabled(b, false); } @NonNull private SpeakerABStatus getSpeakerABStatus( SpeakerACommandMsg.Status speakerA, SpeakerBCommandMsg.Status speakerB) { for (final SpeakerABStatus s : SpeakerABStatus.values()) { if (speakerA == s.speakerA && speakerB == s.speakerB) { return s; } } if (speakerA == SpeakerACommandMsg.Status.ON && speakerB != SpeakerBCommandMsg.Status.ON) { return SpeakerABStatus.A_ONLY; } if (speakerA != SpeakerACommandMsg.Status.ON && speakerB == SpeakerBCommandMsg.Status.ON) { return SpeakerABStatus.B_ONLY; } return SpeakerABStatus.OFF; } }
22,771
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
ShortcutsFragment.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/fragments/ShortcutsFragment.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.fragments; import android.annotation.SuppressLint; import android.content.Context; import android.os.Bundle; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.TextView; import com.mkulesh.onpc.R; import com.mkulesh.onpc.config.CfgAppSettings; import com.mkulesh.onpc.config.CfgFavoriteShortcuts; import com.mkulesh.onpc.iscp.State; import com.mkulesh.onpc.utils.Logging; import com.mobeta.android.dslv.DragSortListView; import java.util.HashSet; import androidx.annotation.NonNull; import androidx.annotation.Nullable; public class ShortcutsFragment extends BaseFragment { private static final String CLIPBOARD_LABEL = "com.mkulesh.onpc.clipboard"; private DragSortListView listView; private ShortcutsListAdapter listViewAdapter; private CfgFavoriteShortcuts.Shortcut selectedItem = null; public ShortcutsFragment() { // Empty constructor required for fragment subclasses } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { initializeFragment(inflater, container, R.layout.shortcuts_fragment, CfgAppSettings.Tabs.SHORTCUTS); listView = rootView.findViewById(R.id.shortcut_list); if (this.getContext() != null) { listViewAdapter = new ShortcutsListAdapter(this.getContext(), activity.getConfiguration().favoriteShortcuts); listView.setAdapter(listViewAdapter); } registerForContextMenu(listView); updateContent(); return rootView; } @Override protected void updateStandbyView(@Nullable final State state) { updateList(state); } @Override protected void updateActiveView(@NonNull final State state, @NonNull final HashSet<State.ChangeType> eventChanges) { // Dismiss update if a data change due to receiver input is detected // In this case, the list will be apdated and drag is cancelled if (eventChanges.size() == State.ChangeType.values().length) { updateList(state); } } private void updateList(@Nullable final State state) { final TextView howto = rootView.findViewById(R.id.shortcut_howto); howto.setVisibility(View.GONE); listView.setVisibility(View.INVISIBLE); if (listViewAdapter == null || state == null) { return; } if (activity.getConfiguration().favoriteShortcuts.getShortcuts().isEmpty()) { final String message = String.format( activity.getResources().getString(R.string.favorite_shortcut_howto), CfgAppSettings.getTabName(activity, CfgAppSettings.Tabs.MEDIA), activity.getResources().getString(R.string.action_context_mobile), activity.getResources().getString(R.string.favorite_shortcut_create)); howto.setText(message); howto.setVisibility(View.VISIBLE); return; } listViewAdapter.setItems(activity.getConfiguration().favoriteShortcuts.getShortcuts()); listView.setVisibility(View.VISIBLE); listView.setOnItemClickListener((adapterView, view, pos, l) -> { selectedItem = (CfgFavoriteShortcuts.Shortcut) listViewAdapter.getItem(pos); if (selectedItem != null && activity.isConnected()) { activity.getStateManager().applyShortcut(activity, selectedItem); activity.setOpenedTab(CfgAppSettings.Tabs.MEDIA); } }); listView.setDropListener((int from, int to) -> listViewAdapter.drop(from, to)); } @Override public void onCreateContextMenu(@NonNull ContextMenu menu, @NonNull View v, ContextMenu.ContextMenuInfo menuInfo) { selectedItem = null; AdapterView.AdapterContextMenuInfo acmi = (AdapterView.AdapterContextMenuInfo) menuInfo; selectedItem = (CfgFavoriteShortcuts.Shortcut) listViewAdapter.getItem(acmi.position); if (selectedItem != null) { Logging.info(this, "Context menu: " + selectedItem); MenuInflater inflater = activity.getMenuInflater(); inflater.inflate(R.menu.favorite_context_menu, menu); } } @SuppressLint("NonConstantResourceId") @Override public boolean onContextItemSelected(@NonNull MenuItem item) { if (selectedItem != null) { Logging.info(this, "Context menu '" + item.getTitle() + "'; " + selectedItem); switch (item.getItemId()) { case R.id.shortcut_menu_edit: final Dialogs dl = new Dialogs(activity); dl.showEditShortcutDialog(selectedItem, this::updateContent); selectedItem = null; return true; case R.id.shortcut_menu_delete: activity.getConfiguration().favoriteShortcuts.deleteShortcut(selectedItem); updateContent(); selectedItem = null; return true; case R.id.shortcut_menu_copy_to_clipboard: copyToClipboard(selectedItem); selectedItem = null; return true; } } selectedItem = null; return super.onContextItemSelected(item); } private void copyToClipboard(CfgFavoriteShortcuts.Shortcut shortcut) { if (activity == null || !activity.isConnected()) { return; } final String data = shortcut.toScript(activity, activity.getStateManager().getState()); try { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) activity .getSystemService(Context.CLIPBOARD_SERVICE); if (clipboard != null) { android.content.ClipData clip = android.content.ClipData.newPlainText(CLIPBOARD_LABEL, data); clipboard.setPrimaryClip(clip); } } catch (Exception e) { // nothing to do } } }
7,035
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
RemoteInterfaceFragment.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/fragments/RemoteInterfaceFragment.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.fragments; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import com.mkulesh.onpc.R; import com.mkulesh.onpc.config.CfgAppSettings; import com.mkulesh.onpc.iscp.State; import com.mkulesh.onpc.iscp.messages.AmpOperationCommandMsg; import com.mkulesh.onpc.iscp.messages.CdPlayerOperationCommandMsg; import java.util.ArrayList; import java.util.HashSet; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.widget.AppCompatImageButton; public class RemoteInterfaceFragment extends BaseFragment { private final ArrayList<View> buttons = new ArrayList<>(); public RemoteInterfaceFragment() { // Empty constructor required for fragment subclasses } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { initializeFragment(inflater, container, R.layout.remote_interface_fragment, CfgAppSettings.Tabs.RI); if (activity.getConfiguration().appSettings.isRemoteInterfaceAmp()) { final LinearLayout l = rootView.findViewById(R.id.remote_interface_amp); l.setVisibility(View.VISIBLE); collectButtons(l, buttons); } if (activity.getConfiguration().appSettings.isRemoteInterfaceCd()) { final LinearLayout l = rootView.findViewById(R.id.remote_interface_cd); l.setVisibility(View.VISIBLE); collectButtons(l, buttons); } for (View b : buttons) { prepareRiButton(b); } updateContent(); return rootView; } private void prepareRiButton(View b) { if (b.getTag() == null) { return; } String[] tokens = b.getTag().toString().split(":"); if (tokens.length != 2) { return; } final String msgName = tokens[0]; switch (msgName) { case AmpOperationCommandMsg.CODE: { final AmpOperationCommandMsg cmd = new AmpOperationCommandMsg(tokens[1]); if (b instanceof AppCompatImageButton) { prepareButton((AppCompatImageButton) b, cmd, cmd.getCommand().getImageId(), cmd.getCommand().getDescriptionId()); } else { prepareButtonListeners(b, cmd, null); } break; } case CdPlayerOperationCommandMsg.CODE: { final CdPlayerOperationCommandMsg cmd = new CdPlayerOperationCommandMsg(tokens[1]); if (b instanceof AppCompatImageButton) { prepareButton((AppCompatImageButton) b, cmd, cmd.getCommand().getImageId(), cmd.getCommand().getDescriptionId()); } else { prepareButtonListeners(b, cmd, null); } break; } default: break; } } @Override protected void updateStandbyView(@Nullable final State state) { for (View b : buttons) { setButtonEnabled(b, state != null); } } @Override protected void updateActiveView(@NonNull final State state, @NonNull final HashSet<State.ChangeType> eventChanges) { for (View b : buttons) { setButtonEnabled(b, true); } } }
4,214
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
PopupManager.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/fragments/PopupManager.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.fragments; import android.graphics.drawable.Drawable; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import com.mkulesh.onpc.MainActivity; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.ConnectionIf; import com.mkulesh.onpc.iscp.PopupBuilder; import com.mkulesh.onpc.iscp.State; import com.mkulesh.onpc.iscp.messages.CustomPopupMsg; import com.mkulesh.onpc.iscp.messages.XmlListItemMsg; import com.mkulesh.onpc.utils.Logging; import com.mkulesh.onpc.utils.Utils; import java.util.List; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; class PopupManager { private AlertDialog trackMenuDialog = null; private LinearLayout trackMenuGroup = null; private AlertDialog popupDialog = null; void showTrackMenuDialog(@NonNull final MainActivity activity, @NonNull final State state) { if (trackMenuDialog == null) { Logging.info(this, "create track menu dialog"); final FrameLayout frameView = new FrameLayout(activity); final Drawable icon = Utils.getDrawable(activity, R.drawable.cmd_track_menu); Utils.setDrawableColorAttr(activity, icon, android.R.attr.textColorSecondary); trackMenuDialog = new AlertDialog.Builder(activity) .setTitle(R.string.cmd_track_menu) .setIcon(icon) .setCancelable(false) .setView(frameView) .setNegativeButton(activity.getResources().getString(R.string.action_cancel), (d, which) -> { if (activity.isConnected() && state.protoType == ConnectionIf.ProtoType.ISCP) { activity.getStateManager().sendMessage(activity.getStateManager().getReturnMessage()); } d.dismiss(); }) .create(); trackMenuDialog.getLayoutInflater().inflate(R.layout.dialog_track_menu, frameView); trackMenuDialog.setOnDismissListener((d) -> { Logging.info(this, "close track menu dialog"); trackMenuDialog = null; trackMenuGroup = null; }); trackMenuGroup = frameView.findViewById(R.id.track_menu_layout); updateTrackMenuGroup(activity, state, trackMenuGroup); trackMenuDialog.show(); Utils.fixDialogLayout(trackMenuDialog, android.R.attr.textColorSecondary); } else if (trackMenuGroup != null) { Logging.info(this, "update track menu dialog"); updateTrackMenuGroup(activity, state, trackMenuGroup); } } private void updateTrackMenuGroup(@NonNull final MainActivity activity, @NonNull final State state, @NonNull LinearLayout trackMenuGroup) { trackMenuGroup.removeAllViews(); final List<XmlListItemMsg> menuItems = state.cloneMediaItems(); for (final XmlListItemMsg msg : menuItems) { if (msg.getTitle() == null || msg.getTitle().isEmpty()) { continue; } Logging.info(this, " menu item: " + msg); final LinearLayout itemView = (LinearLayout) LayoutInflater.from(activity). inflate(R.layout.media_item, trackMenuGroup, false); final View textView = itemView.findViewById(R.id.media_item_title); if (textView != null) { ((TextView) textView).setText(msg.getTitle()); if (!msg.isSelectable()) { ((TextView) textView).setTextColor(Utils.getThemeColorAttr(activity, android.R.attr.textColorSecondary)); ((TextView) textView).setTextSize(TypedValue.COMPLEX_UNIT_PX, activity.getResources().getDimensionPixelSize(R.dimen.secondary_text_size)); } } itemView.setOnClickListener((View v) -> { if (activity.isConnected()) { activity.getStateManager().sendMessage(msg); } if (trackMenuDialog != null) { trackMenuDialog.dismiss(); } }); trackMenuGroup.addView(itemView); } } void closeTrackMenuDialog() { if (trackMenuDialog != null) { Logging.info(this, "close track menu dialog"); trackMenuDialog.setOnDismissListener(null); trackMenuDialog.dismiss(); trackMenuDialog = null; trackMenuGroup = null; } } void showPopupDialog(@NonNull final MainActivity activity, @NonNull final State state) { closePopupDialog(); final CustomPopupMsg inMsg = state.popup.getAndSet(null); if (inMsg == null) { return; } try { PopupBuilder builder = new PopupBuilder(activity, state, (outMsg) -> { if (activity.isConnected()) { activity.getStateManager().sendMessage(outMsg); } }); popupDialog = builder.build(inMsg); if (popupDialog == null) { return; } popupDialog.setOnDismissListener((d) -> { Logging.info(this, "closing popup dialog"); popupDialog = null; }); popupDialog.show(); Utils.fixDialogLayout(popupDialog, android.R.attr.textColorSecondary); } catch (Exception e) { Logging.info(this, "can not create popup dialog: " + e.getLocalizedMessage()); } } void closePopupDialog() { if (popupDialog != null) { Logging.info(this, "closing popup dialog"); popupDialog.setOnDismissListener(null); popupDialog.dismiss(); popupDialog = null; } } }
7,083
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
MediaFilter.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/fragments/MediaFilter.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.fragments; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import com.mkulesh.onpc.MainActivity; import com.mkulesh.onpc.R; import com.mkulesh.onpc.utils.Utils; import androidx.annotation.NonNull; import androidx.appcompat.widget.AppCompatEditText; class MediaFilter { public interface MediaFilterInterface { void onMediaFilterChanged(); } private MainActivity activity = null; private AppCompatEditText filterRegex = null; private boolean enabled; private boolean visible; void init(@NonNull final MainActivity activity, @NonNull final View rootView, @NonNull final MediaFilterInterface mediaFilterInterface) { this.activity = activity; filterRegex = rootView.findViewById(R.id.filter_regex); filterRegex.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) { // empty } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // empty } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (visible) { mediaFilterInterface.onMediaFilterChanged(); } } }); disable(); visible = false; } void enable() { enabled = true; } void disable() { enabled = false; } boolean isEnabled() { return enabled; } @SuppressWarnings("BooleanMethodIsAlwaysInverted") boolean isVisible() { return visible; } void setVisibility(boolean visible, boolean clear) { this.visible = visible; filterRegex.setVisibility(this.visible ? View.VISIBLE : View.GONE); if (activity == null && filterRegex == null) { return; } if (this.visible) { filterRegex.requestFocus(); Utils.showSoftKeyboard(activity, filterRegex, true); } else { Utils.showSoftKeyboard(activity, filterRegex, false); filterRegex.clearFocus(); if (clear && filterRegex.getText() != null) { filterRegex.getText().clear(); } } } boolean ignore(@NonNull String title) { final String filter = (visible && filterRegex != null && filterRegex.getText() != null && filterRegex.getText().length() > 0) ? filterRegex.getText().toString() : null; if (filter == null) { return false; } if (filter.isEmpty() || filter.equals("*")) { return false; } if (title.toUpperCase().startsWith(filter.toUpperCase())) { return false; } if (filter.startsWith("*")) { final String f = filter.substring(filter.lastIndexOf('*') + 1); return !title.toUpperCase().contains(f.toUpperCase()); } return true; } }
3,971
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
ListenFragment.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/fragments/ListenFragment.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.fragments; import android.annotation.SuppressLint; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.HorizontalScrollView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.TextView; import com.mkulesh.onpc.R; import com.mkulesh.onpc.config.CfgAppSettings; import com.mkulesh.onpc.config.CfgAudioControl; import com.mkulesh.onpc.iscp.ConnectionIf; import com.mkulesh.onpc.iscp.ISCPMessage; import com.mkulesh.onpc.iscp.State; import com.mkulesh.onpc.iscp.StateManager; import com.mkulesh.onpc.iscp.messages.AmpOperationCommandMsg; import com.mkulesh.onpc.iscp.messages.AudioMutingMsg; import com.mkulesh.onpc.iscp.messages.CdPlayerOperationCommandMsg; import com.mkulesh.onpc.iscp.messages.DisplayModeMsg; import com.mkulesh.onpc.iscp.messages.InputSelectorMsg; import com.mkulesh.onpc.iscp.messages.ListeningModeMsg; import com.mkulesh.onpc.iscp.messages.MasterVolumeMsg; import com.mkulesh.onpc.iscp.messages.MenuStatusMsg; import com.mkulesh.onpc.iscp.messages.MultiroomChannelSettingMsg; import com.mkulesh.onpc.iscp.messages.MultiroomDeviceInformationMsg; import com.mkulesh.onpc.iscp.messages.NetworkServiceMsg; import com.mkulesh.onpc.iscp.messages.OperationCommandMsg; import com.mkulesh.onpc.iscp.messages.PlayStatusMsg; import com.mkulesh.onpc.iscp.messages.PresetCommandMsg; import com.mkulesh.onpc.iscp.messages.RDSInformationMsg; import com.mkulesh.onpc.iscp.messages.ReceiverInformationMsg; import com.mkulesh.onpc.iscp.messages.ServiceType; import com.mkulesh.onpc.iscp.messages.TimeInfoMsg; import com.mkulesh.onpc.iscp.messages.TimeSeekMsg; import com.mkulesh.onpc.iscp.messages.TuningCommandMsg; import com.mkulesh.onpc.utils.Logging; import com.mkulesh.onpc.utils.Utils; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.AppCompatButton; import androidx.appcompat.widget.AppCompatImageButton; import androidx.appcompat.widget.AppCompatSeekBar; public class ListenFragment extends BaseFragment implements AudioControlManager.MasterVolumeInterface { private HorizontalScrollView listeningModeLayout; private LinearLayout soundControlBtnLayout, soundControlSliderLayout; private AppCompatImageButton btnRepeat; private AppCompatImageButton btnPrevious; private AppCompatImageButton btnPausePlay; private AppCompatImageButton btnNext; private AppCompatImageButton btnRandom; private AppCompatImageButton btnTrackMenu; private AppCompatImageButton btnMultiroomGroup; private AppCompatButton btnMultiroomChanel; private final List<AppCompatImageButton> playbackButtons = new ArrayList<>(); private final List<AppCompatImageButton> fmDabButtons = new ArrayList<>(); private final List<AppCompatImageButton> amplifierButtons = new ArrayList<>(); private AppCompatImageButton positiveFeed, negativeFeed; private final List<View> deviceSoundButtons = new ArrayList<>(); private ImageView cover; private AppCompatSeekBar seekBar; private final AudioControlManager audioControlManager = new AudioControlManager(); public ListenFragment() { // Empty constructor required for fragment subclasses } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { initializeFragment(inflater, container, R.layout.monitor_fragment_port, R.layout.monitor_fragment_land, CfgAppSettings.Tabs.LISTEN); rootView.setLayerType(View.LAYER_TYPE_HARDWARE, null); listeningModeLayout = rootView.findViewById(R.id.listening_mode_layout); soundControlBtnLayout = rootView.findViewById(R.id.sound_control_btn_layout); soundControlSliderLayout = rootView.findViewById(R.id.sound_control_slider_layout); // Command Buttons btnRepeat = rootView.findViewById(R.id.btn_repeat); playbackButtons.add(btnRepeat); btnPrevious = rootView.findViewById(R.id.btn_previous); playbackButtons.add(btnPrevious); final AppCompatImageButton btnStop = rootView.findViewById(R.id.btn_stop); playbackButtons.add(btnStop); btnPausePlay = rootView.findViewById(R.id.btn_pause_play); playbackButtons.add(btnPausePlay); btnNext = rootView.findViewById(R.id.btn_next); playbackButtons.add(btnNext); btnRandom = rootView.findViewById(R.id.btn_random); playbackButtons.add(btnRandom); for (AppCompatImageButton b : playbackButtons) { final OperationCommandMsg msg = new OperationCommandMsg( ReceiverInformationMsg.DEFAULT_ACTIVE_ZONE, (String) (b.getTag())); prepareButton(b, msg, msg.getCommand().getImageId(), msg.getCommand().getDescriptionId()); } // FM/DAB preset and tuning buttons fmDabButtons.add(rootView.findViewById(R.id.btn_preset_up)); fmDabButtons.add(rootView.findViewById(R.id.btn_preset_down)); fmDabButtons.add(rootView.findViewById(R.id.btn_tuning_up)); fmDabButtons.add(rootView.findViewById(R.id.btn_tuning_down)); fmDabButtons.add(rootView.findViewById(R.id.btn_rds_info)); prepareFmDabButtons(); // Audio control buttons audioControlManager.setActivity(activity, this); clearSoundVolumeButtons(); cover = rootView.findViewById(R.id.tv_cover); cover.setContentDescription(activity.getResources().getString(R.string.tv_display_mode)); prepareButtonListeners(cover, new DisplayModeMsg(DisplayModeMsg.TOGGLE)); seekBar = rootView.findViewById(R.id.progress_bar); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { int progressChanged = 0; public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { progressChanged = progress; } public void onStartTrackingTouch(SeekBar seekBar) { // empty } public void onStopTrackingTouch(SeekBar seekBar) { if (activity.isConnected()) { seekTime(progressChanged); } } }); // Track menu { btnTrackMenu = rootView.findViewById(R.id.btn_track_menu); setButtonEnabled(btnTrackMenu, false); } // Multiroom btnMultiroomGroup = rootView.findViewById(R.id.btn_multiroom_group); btnMultiroomChanel = rootView.findViewById(R.id.btn_multiroom_channel); // Feeds positiveFeed = rootView.findViewById(R.id.btn_positive_feed); prepareButtonListeners(positiveFeed, null, () -> activity.getStateManager().sendTrackCmd(OperationCommandMsg.Command.F1, true)); negativeFeed = rootView.findViewById(R.id.btn_negative_feed); prepareButtonListeners(negativeFeed, null, () -> activity.getStateManager().sendTrackCmd(OperationCommandMsg.Command.F2, true)); updateContent(); return rootView; } @Override public void onResume() { super.onResume(); if (activity != null && activity.isConnected()) { activity.getStateManager().setPlaybackMode(true); final State state = activity.getStateManager().getState(); if (state.isUiTypeValid() && !state.isPlaybackMode() && !state.isMenuMode()) { activity.getStateManager().sendMessage(StateManager.LIST_MSG); } } } @Override public void onPause() { super.onPause(); updateStandbyView(null); } private void prepareFmDabButtons() { for (AppCompatImageButton b : fmDabButtons) { String[] tokens = b.getTag().toString().split(":"); if (tokens.length != 2) { continue; } final String msgName = tokens[0]; switch (msgName) { case PresetCommandMsg.CODE: final PresetCommandMsg pMsg = new PresetCommandMsg( ReceiverInformationMsg.DEFAULT_ACTIVE_ZONE, tokens[1]); if (pMsg.getCommand() != null) { prepareButton(b, pMsg, pMsg.getCommand().getImageId(), pMsg.getCommand().getDescriptionId()); } break; case TuningCommandMsg.CODE: final TuningCommandMsg tMsg = new TuningCommandMsg( ReceiverInformationMsg.DEFAULT_ACTIVE_ZONE, tokens[1]); if (tMsg.getCommand() != null) { prepareButton(b, tMsg, tMsg.getCommand().getImageId(), tMsg.getCommand().getDescriptionId()); } break; case RDSInformationMsg.CODE: prepareButton(b, null, R.drawable.cmd_rds_info, R.string.cmd_rds_info); prepareButtonListeners(b, null, () -> { if (activity != null && activity.isConnected()) { final InputSelectorMsg.InputType inp = activity.getStateManager().getState().inputType; final ISCPMessage msg = inp == InputSelectorMsg.InputType.FM ? new RDSInformationMsg(RDSInformationMsg.TOGGLE) : new DisplayModeMsg(DisplayModeMsg.TOGGLE); activity.getStateManager().sendMessage(msg); } }); break; } } } private void clearSoundVolumeButtons() { amplifierButtons.clear(); deviceSoundButtons.clear(); soundControlBtnLayout.removeAllViews(); soundControlBtnLayout.setVisibility(View.GONE); soundControlSliderLayout.removeAllViews(); soundControlSliderLayout.setVisibility(View.GONE); } private void prepareAmplifierButtons() { clearSoundVolumeButtons(); soundControlBtnLayout.setVisibility(View.VISIBLE); listeningModeLayout.setVisibility(View.GONE); final AmpOperationCommandMsg.Command[] commands = new AmpOperationCommandMsg.Command[]{ AmpOperationCommandMsg.Command.AMTTG, AmpOperationCommandMsg.Command.MVLDOWN, AmpOperationCommandMsg.Command.MVLUP }; for (AmpOperationCommandMsg.Command c : commands) { final AmpOperationCommandMsg msg = new AmpOperationCommandMsg(c.getCode()); final AppCompatImageButton b = createButton( msg.getCommand().getImageId(), msg.getCommand().getDescriptionId(), msg, msg.getCommand().getCode()); soundControlBtnLayout.addView(b); amplifierButtons.add(b); } } private void prepareDeviceSoundButtons(final State.SoundControlType soundControl, @NonNull final State state) { clearSoundVolumeButtons(); soundControlBtnLayout.setVisibility(View.VISIBLE); final ConnectionIf.ProtoType protoType = state.protoType; // Here, we create zone-dependent buttons without command message. // The message for active zone will be assigned in updateActiveView final boolean isSlider = soundControl == State.SoundControlType.DEVICE_SLIDER || soundControl == State.SoundControlType.DEVICE_BTN_AROUND_SLIDER || soundControl == State.SoundControlType.DEVICE_BTN_ABOVE_SLIDER; if (isSlider) { if (soundControl == State.SoundControlType.DEVICE_BTN_ABOVE_SLIDER) { audioControlManager.createButtonsSoundControl(this, soundControlBtnLayout); } soundControlSliderLayout.setVisibility(View.VISIBLE); audioControlManager.createSliderSoundControl(this, soundControlSliderLayout, state, soundControl); } else { audioControlManager.createButtonsSoundControl(this, soundControlBtnLayout); } for (int i = 0; i < soundControlBtnLayout.getChildCount(); i++) { deviceSoundButtons.add(soundControlBtnLayout.getChildAt(i)); } for (int i = 0; i < soundControlSliderLayout.getChildCount(); i++) { deviceSoundButtons.add(soundControlSliderLayout.getChildAt(i)); } // fast selector for listening mode listeningModeLayout.setVisibility(View.VISIBLE); final CfgAudioControl ac = activity.getConfiguration().audioControl; if (listeningModeLayout.getChildCount() == 1) { final LinearLayout l = (LinearLayout) listeningModeLayout.getChildAt(0); l.removeAllViews(); for (ListeningModeMsg.Mode m : ac.getSortedListeningModes(true, null, protoType)) { final ListeningModeMsg msg = new ListeningModeMsg(m); final AppCompatButton b = createButton( msg.getMode().getDescriptionId(), msg, msg.getMode(), null); l.addView(b); b.setVisibility(View.GONE); deviceSoundButtons.add(b); } } } private void setButtonsEnabled(List<AppCompatImageButton> buttons, boolean flag) { for (AppCompatImageButton b : buttons) { setButtonEnabled(b, flag); } } private void setButtonsVisibility(List<AppCompatImageButton> buttons, int flag) { for (AppCompatImageButton b : buttons) { b.setVisibility(flag); } } @Override protected void updateStandbyView(@Nullable final State state) { ((TextView) rootView.findViewById(R.id.tv_time_start)).setText(TimeInfoMsg.INVALID_TIME); ((TextView) rootView.findViewById(R.id.tv_time_end)).setText(TimeInfoMsg.INVALID_TIME); TextView track = rootView.findViewById(R.id.tv_track); track.setText(""); updateInputSource(null, R.drawable.media_item_unknown, false); ((TextView) rootView.findViewById(R.id.tv_album)).setText(""); ((TextView) rootView.findViewById(R.id.tv_artist)).setText(""); ((TextView) rootView.findViewById(R.id.tv_title)).setText(""); final TextView format = rootView.findViewById(R.id.tv_file_format); { format.setText(""); format.setClickable(false); } cover.setEnabled(false); cover.setImageResource(R.drawable.empty_cover); Utils.setImageViewColorAttr(activity, cover, android.R.attr.textColor); seekBar.setEnabled(false); seekBar.setProgress(0); setButtonsEnabled(amplifierButtons, state != null); for (View b : deviceSoundButtons) { if (audioControlManager.isVolumeLevel(b)) { updateVolumeLevel(b, state); } else { setButtonEnabled(b, false); } } setButtonsVisibility(playbackButtons, View.VISIBLE); setButtonsEnabled(playbackButtons, false); setButtonsVisibility(fmDabButtons, View.GONE); btnTrackMenu.setVisibility(View.GONE); updateMultiroomGroupBtn(btnMultiroomGroup, state); updateMultiroomChannelBtn(btnMultiroomChanel, state); positiveFeed.setVisibility(View.GONE); negativeFeed.setVisibility(View.GONE); } @Override protected void updateActiveView(@NonNull final State state, @NonNull final HashSet<State.ChangeType> eventChanges) { // time seek only if (eventChanges.size() == 1 && eventChanges.contains(State.ChangeType.TIME_SEEK)) { updateProgressBar(state); return; } if (eventChanges.contains(State.ChangeType.AUDIO_CONTROL)) { audioControlManager.updateActiveView(state); } Logging.info(this, "Updating playback monitor"); // Auto volume control final State.SoundControlType soundControl = state.soundControlType( activity.getConfiguration().audioControl.getSoundControl(), state.getActiveZoneInfo()); switch (soundControl) { case RI_AMP: prepareAmplifierButtons(); break; case DEVICE_BUTTONS: case DEVICE_SLIDER: case DEVICE_BTN_AROUND_SLIDER: case DEVICE_BTN_ABOVE_SLIDER: prepareDeviceSoundButtons(soundControl, state); break; default: clearSoundVolumeButtons(); break; } // Text (album and artist) { ((TextView) rootView.findViewById(R.id.tv_album)).setText(state.album); ((TextView) rootView.findViewById(R.id.tv_artist)).setText(state.artist); final TextView title = rootView.findViewById(R.id.tv_title); final TextView format = rootView.findViewById(R.id.tv_file_format); if (state.isRadioInput()) { final ReceiverInformationMsg.Preset preset = state.searchPreset(); final String presetInfo = preset != null ? preset.displayedString(false) : ""; final TextView album = rootView.findViewById(R.id.tv_album); album.setText(presetInfo); final String stationInfo = state.isDab() || state.isFm() ? state.stationName : ""; title.setText(!stationInfo.equals(presetInfo) ? stationInfo : ""); format.setText(String.format(" %s", state.getFrequencyInfo(activity))); } else { title.setText(state.title); format.setText(state.fileFormat); } format.setClickable(state.protoType == ConnectionIf.ProtoType.ISCP); format.setOnClickListener((v) -> { final Dialogs dl = new Dialogs(activity); dl.showAvInfoDialog(state); }); } // service icon and track { final TextView track = rootView.findViewById(R.id.tv_track); track.setText(state.getTrackInfo(activity)); updateInputSource(state, state.getServiceIcon(), true); } // cover cover.setEnabled(true); if (state.cover == null || state.isSimpleInput()) { cover.setImageResource(R.drawable.empty_cover); Utils.setImageViewColorAttr(activity, cover, android.R.attr.textColor); } else { cover.setColorFilter(null); cover.setImageBitmap(state.cover); } // progress bar updateProgressBar(state); // buttons final ArrayList<String> selectedListeningModes = new ArrayList<>(); final CfgAudioControl ac = activity.getConfiguration().audioControl; for (ListeningModeMsg.Mode m : ac.getSortedListeningModes(false, state.listeningMode, state.protoType)) { selectedListeningModes.add(m.getCode()); } setButtonsEnabled(amplifierButtons, true); for (View b : deviceSoundButtons) { setButtonEnabled(b, true); if (b.getTag() instanceof AudioMutingMsg.Status) { setButtonSelected(b, state.audioMuting == AudioMutingMsg.Status.ON); prepareButtonListeners(b, new AudioMutingMsg( state.getActiveZone(), AudioMutingMsg.toggle(state.audioMuting, state.protoType))); } else if (b.getTag() instanceof MasterVolumeMsg.Command) { final MasterVolumeMsg.Command cmd = (MasterVolumeMsg.Command) (b.getTag()); prepareButtonListeners(b, new MasterVolumeMsg(state.getActiveZone(), cmd)); if (audioControlManager.isAudioControlEnabled()) { b.setOnLongClickListener(v -> audioControlManager.showAudioControlDialog()); } else { b.setOnLongClickListener(v -> Utils.showButtonDescription(activity, v)); } } else if (b.getTag() instanceof ListeningModeMsg.Mode) { final ListeningModeMsg.Mode s = (ListeningModeMsg.Mode) (b.getTag()); if (selectedListeningModes.contains(s.getCode())) { b.setVisibility(View.VISIBLE); setButtonSelected(b, s == state.listeningMode); if (b.isSelected()) { b.getParent().requestChildFocus(b, b); } } else { b.setVisibility(View.GONE); } } else if (audioControlManager.isVolumeLevel(b)) { updateVolumeLevel(b, state); } } // Track menu and playback buttons if (state.protoType == ConnectionIf.ProtoType.ISCP || state.isRadioInput()) { prepareButton(btnTrackMenu, null, R.drawable.cmd_track_menu, R.string.cmd_track_menu); final boolean isTrackMenu = state.isRadioInput() || state.isTrackMenuActive(); btnTrackMenu.setVisibility(View.VISIBLE); setButtonEnabled(btnTrackMenu, isTrackMenu); if (state.isRadioInput()) { updatePresetButtons(); prepareButtonListeners(btnTrackMenu, null, () -> { final Dialogs dl = new Dialogs(activity); dl.showPresetMemoryDialog(state); }); } else { updatePlaybackButtons(state); prepareButtonListeners(btnTrackMenu, null, () -> activity.getStateManager().sendTrackCmd(OperationCommandMsg.Command.MENU, false)); } } else if (state.protoType == ConnectionIf.ProtoType.DCP && state.inputType == InputSelectorMsg.InputType.DCP_NET) { prepareButton(btnTrackMenu, null, ServiceType.DCP_PLAYQUEUE.getImageId(), ServiceType.DCP_PLAYQUEUE.getDescriptionId()); btnTrackMenu.setVisibility(View.VISIBLE); setButtonEnabled(btnTrackMenu, true); updatePlaybackButtons(state); prepareButtonListeners(btnTrackMenu, null, () -> { activity.getStateManager().sendMessage(new NetworkServiceMsg(ServiceType.DCP_PLAYQUEUE)); activity.setOpenedTab(CfgAppSettings.Tabs.MEDIA); }); } else { btnTrackMenu.setVisibility(View.GONE); } if (state.isMenuMode() && !state.isMediaEmpty()) { popupManager.showTrackMenuDialog(activity, state); } else { popupManager.closeTrackMenuDialog(); } // Multiroom groups updateMultiroomGroupBtn(btnMultiroomGroup, state); updateMultiroomChannelBtn(btnMultiroomChanel, state); // Feeds updateFeedButton(positiveFeed, state.positiveFeed, state.serviceType); updateFeedButton(negativeFeed, state.negativeFeed, state.serviceType); } private void updatePresetButtons() { setButtonsVisibility(playbackButtons, View.GONE); setButtonsVisibility(fmDabButtons, View.VISIBLE); setButtonsEnabled(fmDabButtons, true); } private void updateInputSource(@Nullable final State state, @DrawableRes int imageId, final boolean visible) { final AppCompatImageButton btn = rootView.findViewById(R.id.btn_input_selector); prepareButton(btn, imageId, R.string.av_info_dialog); btn.setVisibility(visible ? View.VISIBLE : View.GONE); setButtonEnabled(btn, state != null && state.protoType == ConnectionIf.ProtoType.ISCP); prepareButtonListeners(btn, null, () -> { final Dialogs dl = new Dialogs(activity); dl.showAvInfoDialog(state); }); } /* * Playback control */ private void updatePlaybackButtons(@NonNull final State state) { setButtonsVisibility(fmDabButtons, View.GONE); setButtonsVisibility(playbackButtons, View.VISIBLE); for (AppCompatImageButton b : playbackButtons) { String opCommand = (String) (b.getTag()); if (b.getId() == btnPausePlay.getId()) { // For common btnPausePlay button, set desired command (PLAY or PAUSE) // depending on current play state final boolean isPaused = (state.playStatus == PlayStatusMsg.PlayStatus.STOP || state.playStatus == PlayStatusMsg.PlayStatus.PAUSE); opCommand = isPaused ? OperationCommandMsg.Command.PLAY.toString() : OperationCommandMsg.Command.PAUSE.toString(); } if (state.isCdInput()) { final String ccdCommand = CdPlayerOperationCommandMsg.convertOpCommand(opCommand); final CdPlayerOperationCommandMsg msg = new CdPlayerOperationCommandMsg(ccdCommand); prepareButton(b, msg, msg.getCommand().getImageId(), msg.getCommand().getDescriptionId()); } else if (state.protoType == ConnectionIf.ProtoType.DCP) { final OperationCommandMsg.Command netCommand = (OperationCommandMsg.Command) ISCPMessage.searchParameter(opCommand, OperationCommandMsg.Command.values(), null); final OperationCommandMsg msg = new OperationCommandMsg(netCommand); prepareButton(b, msg, msg.getCommand().getImageId(), msg.getCommand().getDescriptionId()); } else { final OperationCommandMsg.Command netCommand = (OperationCommandMsg.Command) ISCPMessage.searchParameter(opCommand, OperationCommandMsg.Command.values(), null); prepareButton(b, netCommand.getImageId(), netCommand.getDescriptionId()); // To start play in normal mode, PAUSE shall be issue instead of PLAY command final OperationCommandMsg msg = (netCommand == OperationCommandMsg.Command.PLAY) ? new OperationCommandMsg(state.getActiveZone(), OperationCommandMsg.Command.PAUSE.toString()) : new OperationCommandMsg(state.getActiveZone(), netCommand.toString()); prepareButtonListeners(b, null, () -> { if (activity.getStateManager() != null) { if (!state.isPlaybackMode() && state.isUsb() && (msg.getCommand() == OperationCommandMsg.Command.TRDN || msg.getCommand() == OperationCommandMsg.Command.TRUP)) { // Issue-44: on some receivers, "TRDN" and "TRUP" for USB only work // in playback mode. Therefore, switch to this mode before // send OperationCommandMsg if current mode is LIST activity.getStateManager().sendTrackMsg(msg, false); } else { activity.getStateManager().sendMessage(msg); } } }); } setButtonEnabled(b, true); } if (state.repeatStatus == PlayStatusMsg.RepeatStatus.DISABLE) { setButtonEnabled(btnRepeat, false); } else { final OperationCommandMsg msg = new OperationCommandMsg( OperationCommandMsg.toggleRepeat(state.protoType, state.repeatStatus)); prepareButton(btnRepeat, msg, state.repeatStatus.getImageId(), msg.getCommand().getDescriptionId()); setButtonEnabled(btnRepeat, true); setButtonSelected(btnRepeat, state.repeatStatus != PlayStatusMsg.RepeatStatus.OFF); } if (state.shuffleStatus == PlayStatusMsg.ShuffleStatus.DISABLE) { setButtonEnabled(btnRandom, false); } else { final OperationCommandMsg msg = new OperationCommandMsg( OperationCommandMsg.toggleShuffle(state.protoType, state.shuffleStatus)); prepareButton(btnRandom, msg, msg.getCommand().getImageId(), msg.getCommand().getDescriptionId()); setButtonEnabled(btnRandom, true); setButtonSelected(btnRandom, state.shuffleStatus != PlayStatusMsg.ShuffleStatus.OFF); } setButtonEnabled(btnPrevious, state.isPlaying()); setButtonEnabled(btnNext, state.isPlaying()); setButtonEnabled(btnPausePlay, state.isOn()); } /* * Multiroom control */ private void updateMultiroomGroupBtn(AppCompatImageButton b, @Nullable final State state) { if (state != null && state.protoType == ConnectionIf.ProtoType.ISCP && activity.isMultiroomAvailable()) { b.setVisibility(View.VISIBLE); setButtonEnabled(b, true); setButtonSelected(b, state.isMasterDevice()); b.setContentDescription(activity.getString(R.string.cmd_multiroom_group)); prepareButtonListeners(b, null, () -> { if (activity.isConnected()) { final AlertDialog alertDialog = MultiroomManager.createDeviceSelectionDialog( activity, b.getContentDescription()); alertDialog.show(); Utils.fixDialogLayout(alertDialog, android.R.attr.textColorSecondary); } }); } else { b.setVisibility(View.GONE); setButtonEnabled(b, false); } } private void updateMultiroomChannelBtn(AppCompatButton b, @Nullable final State state) { MultiroomDeviceInformationMsg.ChannelType ch = state != null ? state.multiroomChannel : MultiroomDeviceInformationMsg.ChannelType.NONE; if (ch != MultiroomDeviceInformationMsg.ChannelType.NONE && activity.isMultiroomAvailable()) { final MultiroomChannelSettingMsg cmd = new MultiroomChannelSettingMsg( state.getActiveZone() + 1, MultiroomChannelSettingMsg.getUpType(ch)); b.setVisibility(View.VISIBLE); b.setText(ch.toString()); setButtonEnabled(b, state.isOn()); final Drawable icon = Utils.getDrawable(activity, R.drawable.cmd_multiroom_channel); Utils.setDrawableColorAttr(activity, icon, state.isOn() ? R.attr.colorButtonEnabled : R.attr.colorButtonDisabled); b.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null); prepareButtonListeners(b, cmd, null); } else { b.setVisibility(View.GONE); setButtonEnabled(b, false); b.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); } } /* * Volume control */ @SuppressLint("SetTextI18n") private void updateVolumeLevel(View view, @Nullable final State state) { final boolean volumeValid = state != null && state.isOn() && state.volumeLevel != MasterVolumeMsg.NO_LEVEL; if (view instanceof AppCompatButton) { final AppCompatButton b = (AppCompatButton) view; final Drawable icon = Utils.getDrawable(activity, R.drawable.volume_audio_control); b.setText(volumeValid ? State.getVolumeLevelStr(state.volumeLevel, state.getActiveZoneInfo()) : ""); setButtonEnabled(b, volumeValid); Utils.setDrawableColorAttr(activity, icon, volumeValid ? R.attr.colorButtonEnabled : R.attr.colorButtonDisabled); b.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null); } else if (view instanceof AppCompatSeekBar) { final AppCompatSeekBar b = (AppCompatSeekBar) view; if (volumeValid) { final ReceiverInformationMsg.Zone zone = state.getActiveZoneInfo(); final int maxVolume = Math.min(audioControlManager.getVolumeMax(state, zone), activity.getConfiguration().audioControl.getMasterVolumeMax()); b.setMax(maxVolume); b.setProgress(Math.max(0, state.volumeLevel)); } else { b.setMax(10); b.setProgress(0); } b.setEnabled(volumeValid); } else if (view instanceof TextView) { if (volumeValid) { final ReceiverInformationMsg.Zone zone = state.getActiveZoneInfo(); final int maxVolume = Math.min(audioControlManager.getVolumeMax(state, zone), activity.getConfiguration().audioControl.getMasterVolumeMax()); ((TextView) view).setText(State.getVolumeLevelStr(maxVolume, zone)); } else { ((TextView) view).setText("100"); } } } @Override public void onMasterVolumeMaxUpdate(@NonNull final State state) { // This callback is called if master volume maximum is changed. // We shall re-scale master volume slider if it is visible for (View view : deviceSoundButtons) { if (audioControlManager.isVolumeLevel(view)) { updateVolumeLevel(view, state); } } } @Override public void onMasterVolumeChange(int progressChanged) { // This callback is called when master volume slider is changed. // We shall update the text of the "Audio control" button if (!activity.isConnected()) { return; } final State state = activity.getStateManager().getState(); for (View view : deviceSoundButtons) { if (view instanceof AppCompatButton && audioControlManager.isVolumeLevel(view)) { final AppCompatButton b = (AppCompatButton) view; final String vol = State.getVolumeLevelStr(progressChanged, state.getActiveZoneInfo()); b.setText(vol); } } } /* * Time-seek control */ private void updateProgressBar(@NonNull final State state) { ((TextView) rootView.findViewById(R.id.tv_time_start)).setText(state.currentTime); ((TextView) rootView.findViewById(R.id.tv_time_end)).setText(state.maxTime); final int currTime = Utils.timeToSeconds(state.currentTime); final int maxTime = Utils.timeToSeconds(state.maxTime); if (currTime >= 0 && maxTime >= 0) { seekBar.setMax(maxTime); seekBar.setProgress(currTime); } else { seekBar.setMax(1000); seekBar.setProgress(0); } seekBar.setEnabled(state.isPlaying() && state.timeSeek == MenuStatusMsg.TimeSeek.ENABLE); } private void seekTime(int newSec) { final State state = activity.getStateManager().getState(); final int currTime = Utils.timeToSeconds(state.currentTime); final int maxTime = Utils.timeToSeconds(state.maxTime); if (currTime >= 0 && maxTime >= 0) { final int hour = newSec / 3600; final int min = (newSec - hour * 3600) / 60; final int sec = newSec - hour * 3600 - min * 60; activity.getStateManager().requestSkipNextTimeMsg(2); final TimeSeekMsg msg = new TimeSeekMsg(state.getModel(), hour, min, sec); state.currentTime = msg.getTimeAsString(); ((TextView) rootView.findViewById(R.id.tv_time_start)).setText(state.currentTime); activity.getStateManager().sendMessage(msg); } } private void updateFeedButton(final AppCompatImageButton btn, final MenuStatusMsg.Feed feed, ServiceType serviceType) { btn.setVisibility(feed.isImageValid() ? View.VISIBLE : View.GONE); if (feed.isImageValid()) { btn.setImageResource(feed.getImageId()); setButtonEnabled(btn, true); final boolean isSelected = serviceType == ServiceType.AMAZON_MUSIC ? feed == MenuStatusMsg.Feed.LIKE : feed == MenuStatusMsg.Feed.LOVE; setButtonSelected(btn, isSelected); } } }
38,176
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
ShortcutsListAdapter.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/fragments/ShortcutsListAdapter.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.fragments; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import com.mkulesh.onpc.R; import com.mkulesh.onpc.config.CfgFavoriteShortcuts; import com.mkulesh.onpc.widgets.DraggableItemView; import java.util.ArrayList; import java.util.Collections; import java.util.List; class ShortcutsListAdapter extends BaseAdapter { private final LayoutInflater inflater; private final List<CfgFavoriteShortcuts.Shortcut> items = new ArrayList<>(); private final CfgFavoriteShortcuts favoriteShortcuts; ShortcutsListAdapter(Context context, final CfgFavoriteShortcuts favoriteShortcuts) { this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.favoriteShortcuts = favoriteShortcuts; } void setItems(final List<CfgFavoriteShortcuts.Shortcut> newItems) { items.clear(); for (CfgFavoriteShortcuts.Shortcut d : newItems) { items.add(new CfgFavoriteShortcuts.Shortcut(d, d.alias)); } //noinspection ComparatorCombinators Collections.sort(items, (o1, o2) -> Integer.compare(o1.order, o2.order)); notifyDataSetChanged(); } @Override public int getCount() { return items.size(); } @Override public Object getItem(int position) { return position < items.size() ? items.get(position) : null; } @Override public long getItemId(int position) { return position < items.size() ? items.get(position).id : 0; } @Override public boolean hasStableIds() { return true; } @Override public View getView(int position, View convert, ViewGroup parent) { DraggableItemView view; if (convert == null) { view = (DraggableItemView) inflater.inflate(R.layout.draggable_item_view, parent, false); } else { view = (DraggableItemView) convert; } final CfgFavoriteShortcuts.Shortcut d = items.get(position); view.setTag(d.id); view.setText(d.alias); view.setCheckBoxVisibility(View.GONE); view.setImage(d.getIcon()); return view; } void drop(int from, int to) { if (from != to && from < items.size() && to < items.size()) { CfgFavoriteShortcuts.Shortcut p = items.remove(from); items.add(to, p); favoriteShortcuts.reorder(items); } notifyDataSetChanged(); } }
3,318
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
AudioControlManager.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/fragments/AudioControlManager.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.fragments; import android.annotation.SuppressLint; import android.content.Context; import android.os.Build; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.TextView; import com.mkulesh.onpc.MainActivity; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.State; import com.mkulesh.onpc.iscp.messages.AudioMutingMsg; import com.mkulesh.onpc.iscp.messages.CenterLevelCommandMsg; import com.mkulesh.onpc.iscp.messages.DirectCommandMsg; import com.mkulesh.onpc.iscp.messages.MasterVolumeMsg; import com.mkulesh.onpc.iscp.messages.ReceiverInformationMsg; import com.mkulesh.onpc.iscp.messages.SubwooferLevelCommandMsg; import com.mkulesh.onpc.iscp.messages.ToneCommandMsg; import com.mkulesh.onpc.utils.Logging; import com.mkulesh.onpc.utils.Utils; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.view.ContextThemeWrapper; import androidx.appcompat.widget.AppCompatButton; import androidx.appcompat.widget.AppCompatImageButton; import androidx.appcompat.widget.AppCompatSeekBar; class AudioControlManager { final static private String VOLUME_LEVEL = "volume_level"; public interface MasterVolumeInterface { void onMasterVolumeMaxUpdate(@NonNull final State state); void onMasterVolumeChange(int progressChanged); } private MainActivity activity = null; private MasterVolumeInterface masterVolumeInterface = null; private boolean forceAudioControl = false; private AlertDialog audioControlDialog = null; private LinearLayout volumeGroup = null; private LinearLayout toneBassGroup = null; private LinearLayout toneTrebleGroup = null; private LinearLayout toneDirectGroup = null; private LinearLayout subwooferLevelGroup = null; private LinearLayout centerLevelGroup = null; void setActivity(MainActivity activity, MasterVolumeInterface masterVolumeInterface) { this.activity = activity; this.masterVolumeInterface = masterVolumeInterface; if (activity != null) { this.forceAudioControl = activity.getConfiguration().audioControl.isForceAudioControl(); } } boolean isAudioControlEnabled() { return activity != null && activity.isConnected() && activity.getStateManager().getState().isOn(); } boolean isVolumeLevel(View b) { return b.getTag() != null && b.getTag() instanceof String && VOLUME_LEVEL.equals(b.getTag()); } private boolean isDirectCmdAvailable(@NonNull final State state) { return state.toneDirect != DirectCommandMsg.Status.NONE; } private boolean isDirectMode(@NonNull final State state) { return (isDirectCmdAvailable(state) && state.toneDirect == DirectCommandMsg.Status.ON) || (state.listeningMode != null && state.listeningMode.isDirectMode()); } boolean showAudioControlDialog() { if (!isAudioControlEnabled()) { return false; } Logging.info(this, "open audio control dialog"); final State state = activity.getStateManager().getState(); final FrameLayout frameView = new FrameLayout(activity); activity.getLayoutInflater().inflate(R.layout.dialog_master_volume_layout, frameView); // Master volume volumeGroup = frameView.findViewById(R.id.volume_group); prepareVolumeGroup(state, volumeGroup); // Tone direct toneDirectGroup = frameView.findViewById(R.id.tone_direct_layout); if (isDirectCmdAvailable(state)) { final CheckBox checkBox = toneDirectGroup.findViewById(R.id.tone_direct_checkbox); checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> { activity.getStateManager().sendMessage(new DirectCommandMsg( isChecked ? DirectCommandMsg.Status.ON : DirectCommandMsg.Status.OFF)); final String toneCommand = state.getActiveZone() < ToneCommandMsg.ZONE_COMMANDS.length ? ToneCommandMsg.ZONE_COMMANDS[state.getActiveZone()] : null; if (toneCommand != null) { activity.getStateManager().sendQueries(new String[]{ toneCommand }, "requesting tone state"); } }); } // Tone control toneBassGroup = frameView.findViewById(R.id.bass_group); prepareToneControl( state, ToneCommandMsg.BASS_KEY, toneBassGroup, R.string.tone_bass); toneTrebleGroup = frameView.findViewById(R.id.treble_group); prepareToneControl( state, ToneCommandMsg.TREBLE_KEY, toneTrebleGroup, R.string.tone_treble); // Level for single channels subwooferLevelGroup = frameView.findViewById(R.id.subwoofer_level_group); prepareToneControl( state, SubwooferLevelCommandMsg.KEY, subwooferLevelGroup, R.string.subwoofer_level); centerLevelGroup = frameView.findViewById(R.id.center_level_group); prepareToneControl( state, CenterLevelCommandMsg.KEY, centerLevelGroup, R.string.center_level); final Dialogs dl = new Dialogs(activity); audioControlDialog = dl.createOkDialog(frameView, R.drawable.volume_audio_control, R.string.app_control_audio_control); audioControlDialog.setOnDismissListener((d) -> { Logging.info(this, "closing audio control dialog"); audioControlDialog = null; volumeGroup = null; toneBassGroup = null; toneTrebleGroup = null; toneDirectGroup = null; subwooferLevelGroup = null; centerLevelGroup = null; }); updateActiveView(state); audioControlDialog.show(); Utils.fixDialogLayout(audioControlDialog, android.R.attr.textColorSecondary); return true; } void updateActiveView(@NonNull final State state) { if (audioControlDialog == null) { return; } Logging.info(this, "Updating audio control dialog"); if (volumeGroup != null) { updateVolumeGroup(state, volumeGroup); } if (toneDirectGroup != null) { updateToneDirect(state, toneDirectGroup); } if (toneBassGroup != null) { updateToneGroup( state, ToneCommandMsg.BASS_KEY, toneBassGroup, R.string.tone_bass, isDirectMode(state) ? ToneCommandMsg.NO_LEVEL : state.bassLevel, ToneCommandMsg.NO_LEVEL, ToneCommandMsg.ZONE_COMMANDS.length); } if (toneTrebleGroup != null) { updateToneGroup( state, ToneCommandMsg.TREBLE_KEY, toneTrebleGroup, R.string.tone_treble, isDirectMode(state) ? ToneCommandMsg.NO_LEVEL : state.trebleLevel, ToneCommandMsg.NO_LEVEL, ToneCommandMsg.ZONE_COMMANDS.length); } if (subwooferLevelGroup != null) { updateToneGroup( state, SubwooferLevelCommandMsg.KEY, subwooferLevelGroup, R.string.subwoofer_level, state.subwooferLevel, SubwooferLevelCommandMsg.NO_LEVEL, 1); } if (centerLevelGroup != null) { updateToneGroup( state, CenterLevelCommandMsg.KEY, centerLevelGroup, R.string.center_level, state.centerLevel, CenterLevelCommandMsg.NO_LEVEL, 1); } } private void updateProgressLabel(@NonNull final ViewGroup group, @StringRes final int labelId, final String value) { final TextView labelField = group.findViewWithTag("tone_label"); try { if (labelField != null) { final String labelText = activity.getString(labelId) + ": " + value; labelField.setText(labelText); } } catch (Exception e) { labelField.setText(""); } } private void prepareVolumeGroup(@NonNull final State state, @NonNull final LinearLayout group) { final AppCompatImageButton maxVolumeBtn = group.findViewWithTag("tone_extended_cmd"); { maxVolumeBtn.setVisibility(View.VISIBLE); maxVolumeBtn.setImageResource(R.drawable.volume_max_limit); maxVolumeBtn.setContentDescription(activity.getString(R.string.master_volume_restrict)); maxVolumeBtn.setLongClickable(true); maxVolumeBtn.setOnLongClickListener(v -> Utils.showButtonDescription(activity, v)); maxVolumeBtn.setClickable(true); maxVolumeBtn.setOnClickListener(v -> showMasterVolumeMaxDialog(state)); Utils.setButtonEnabled(activity, maxVolumeBtn, true); } final AppCompatSeekBar progressBar = group.findViewWithTag("tone_progress_bar"); progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { int progressChanged = 0; public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { progressChanged = progress; updateProgressLabel(group, R.string.master_volume, State.getVolumeLevelStr(progressChanged, state.getActiveZoneInfo())); } public void onStartTrackingTouch(SeekBar seekBar) { // empty } public void onStopTrackingTouch(SeekBar seekBar) { if (isAudioControlEnabled()) { activity.getStateManager().sendMessage( new MasterVolumeMsg(state.getActiveZone(), progressChanged)); } } }); } public int getVolumeMax(@NonNull final State state, @Nullable final ReceiverInformationMsg.Zone zone) { final int scale = (zone != null && zone.getVolumeStep() == 0) ? 2 : 1; return (zone != null && zone.getVolMax() > 0) ? scale * zone.getVolMax() : Math.max(state.volumeLevel, scale * MasterVolumeMsg.MAX_VOLUME_1_STEP); } private void updateVolumeGroup(@NonNull final State state, @NonNull final LinearLayout group) { final AppCompatSeekBar progressBar = group.findViewWithTag("tone_progress_bar"); final ReceiverInformationMsg.Zone zone = state.getActiveZoneInfo(); final int maxVolume = Math.min(getVolumeMax(state, zone), activity.getConfiguration().audioControl.getMasterVolumeMax()); updateProgressLabel(group, R.string.master_volume, State.getVolumeLevelStr(state.volumeLevel, zone)); final TextView minValue = group.findViewWithTag("tone_min_value"); minValue.setText("0"); final TextView maxValue = group.findViewWithTag("tone_max_value"); maxValue.setText(State.getVolumeLevelStr(maxVolume, zone)); progressBar.setMax(maxVolume); progressBar.setProgress(Math.max(0, state.volumeLevel)); } private void showMasterVolumeMaxDialog(@NonNull final State state) { final FrameLayout frameView = new FrameLayout(activity); activity.getLayoutInflater().inflate(R.layout.dialog_master_volume_max, frameView); final ReceiverInformationMsg.Zone zone = state.getActiveZoneInfo(); final int maxVolume = getVolumeMax(state, zone); final TextView minValue = frameView.findViewWithTag("tone_min_value"); minValue.setText("0"); final TextView maxValue = frameView.findViewWithTag("tone_max_value"); maxValue.setText(State.getVolumeLevelStr(maxVolume, zone)); final AppCompatSeekBar progressBar = frameView.findViewWithTag("tone_progress_bar"); progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { int progressChanged = 0; public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { progressChanged = progress; updateProgressLabel(frameView, R.string.master_volume_max, State.getVolumeLevelStr(progressChanged, state.getActiveZoneInfo())); } public void onStartTrackingTouch(SeekBar seekBar) { // empty } public void onStopTrackingTouch(SeekBar seekBar) { activity.getConfiguration().audioControl.setMasterVolumeMax(progressChanged); } }); progressBar.setMax(maxVolume); progressBar.setProgress(Math.min(maxVolume, activity.getConfiguration().audioControl.getMasterVolumeMax())); final Dialogs dl = new Dialogs(activity); final AlertDialog masterVolumeMaxDialog = dl.createOkDialog(frameView, R.drawable.volume_max_limit, R.string.master_volume_restrict); masterVolumeMaxDialog.setOnDismissListener((d) -> { if (volumeGroup != null) { updateVolumeGroup(state, volumeGroup); } if (masterVolumeInterface != null) { masterVolumeInterface.onMasterVolumeMaxUpdate(state); } }); masterVolumeMaxDialog.show(); Utils.fixDialogLayout(masterVolumeMaxDialog, android.R.attr.textColorSecondary); } private void prepareToneControl(@NonNull final State state, @NonNull final String toneKey, @NonNull final LinearLayout group, @StringRes final int labelId) { final AppCompatSeekBar progressBar = group.findViewWithTag("tone_progress_bar"); progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { final ReceiverInformationMsg.ToneControl toneControl = state.getToneControl(toneKey, forceAudioControl); int progressChanged = 0; private int getScaledProgress() { if (toneControl == null) { return 0; } final float step = toneControl.getStep() == 0 ? 0.5f : toneControl.getStep(); return (int) ((float) progressChanged * step) + toneControl.getMin(); } public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { progressChanged = progress; updateProgressLabel(group, labelId, Integer.toString(getScaledProgress())); } public void onStartTrackingTouch(SeekBar seekBar) { // empty } public void onStopTrackingTouch(SeekBar seekBar) { if (isAudioControlEnabled()) { final int zone = state.getActiveZone(); switch (toneKey) { case ToneCommandMsg.BASS_KEY: activity.getStateManager().sendMessage( new ToneCommandMsg(zone, getScaledProgress(), ToneCommandMsg.NO_LEVEL)); break; case ToneCommandMsg.TREBLE_KEY: activity.getStateManager().sendMessage( new ToneCommandMsg(zone, ToneCommandMsg.NO_LEVEL, getScaledProgress())); break; case SubwooferLevelCommandMsg.KEY: activity.getStateManager().sendMessage(new SubwooferLevelCommandMsg(getScaledProgress(), state.subwooferCmdLength)); break; case CenterLevelCommandMsg.KEY: activity.getStateManager().sendMessage(new CenterLevelCommandMsg(getScaledProgress(), state.centerCmdLength)); break; } } } }); } @SuppressLint("SetTextI18n") private void updateToneGroup(@NonNull final State state, @NonNull final String toneKey, @NonNull final LinearLayout group, @StringRes final int labelId, int toneLevel, final int noLevel, final int maxZone) { final AppCompatSeekBar progressBar = group.findViewWithTag("tone_progress_bar"); final ReceiverInformationMsg.ToneControl toneControl = state.getToneControl(toneKey, forceAudioControl); final boolean isTone = toneControl != null && toneLevel != noLevel && state.getActiveZone() < maxZone; group.setVisibility(isTone ? View.VISIBLE : View.GONE); if (isTone) { updateProgressLabel(group, labelId, Integer.toString(toneLevel)); final TextView minText = group.findViewWithTag("tone_min_value"); if (minText != null) { minText.setText(Integer.toString(toneControl.getMin())); } final TextView maxText = group.findViewWithTag("tone_max_value"); if (maxText != null) { maxText.setText(Integer.toString(toneControl.getMax())); } final float step = toneControl.getStep() == 0 ? 0.5f : toneControl.getStep(); final int max = (int) ((float) (toneControl.getMax() - toneControl.getMin()) / step); final int progress = (int) ((float) (toneLevel - toneControl.getMin()) / step); progressBar.setMax(max); progressBar.setProgress(progress); } } private void updateToneDirect(@NonNull final State state, @NonNull LinearLayout group) { toneDirectGroup.setVisibility(isDirectCmdAvailable(state) || isDirectMode(state) ? View.VISIBLE : View.GONE); final CheckBox checkBox = group.findViewById(R.id.tone_direct_checkbox); checkBox.setChecked(isDirectMode(state)); checkBox.setEnabled(isDirectCmdAvailable(state)); } void createButtonsSoundControl( @NonNull final BaseFragment fragment, @NonNull final LinearLayout layout) { // audio muting { final AudioMutingMsg.Status status = AudioMutingMsg.Status.TOGGLE; layout.addView(fragment.createButton( R.drawable.volume_amp_muting, status.getDescriptionId(), null, status)); } // volume down { final MasterVolumeMsg.Command cmd = MasterVolumeMsg.Command.DOWN; layout.addView(fragment.createButton( cmd.getImageId(), cmd.getDescriptionId(), null, cmd)); } // master volume label { final AppCompatButton b = fragment.createButton( R.string.dashed_string, null, VOLUME_LEVEL, null); ((LinearLayout.LayoutParams) b.getLayoutParams()).setMargins(0, 0, 0, 0); b.setContentDescription(activity.getResources().getString(R.string.app_control_audio_control)); fragment.prepareButtonListeners(b, null, this::showAudioControlDialog); layout.addView(b); } // volume up { final MasterVolumeMsg.Command cmd = MasterVolumeMsg.Command.UP; layout.addView(fragment.createButton( cmd.getImageId(), cmd.getDescriptionId(), null, cmd)); } } void createSliderSoundControl( @NonNull final BaseFragment fragment, @NonNull final LinearLayout layout, @NonNull final State state, final State.SoundControlType soundControl) { if (soundControl != State.SoundControlType.DEVICE_BTN_ABOVE_SLIDER) { final AppCompatButton b = fragment.createButton( R.string.dashed_string, null, VOLUME_LEVEL, null); b.setContentDescription(activity.getResources().getString(R.string.app_control_audio_control)); fragment.prepareButtonListeners(b, null, this::showAudioControlDialog); layout.addView(b); } if (soundControl == State.SoundControlType.DEVICE_BTN_AROUND_SLIDER) // volume down { final MasterVolumeMsg.Command cmd = MasterVolumeMsg.Command.DOWN; layout.addView(fragment.createButton( cmd.getImageId(), cmd.getDescriptionId(), null, cmd)); } if (soundControl == State.SoundControlType.DEVICE_BTN_ABOVE_SLIDER) { layout.addView(createTextView(fragment.getContext(), null, "0", R.style.SecondaryTextViewStyle)); } // slider { ContextThemeWrapper wrappedContext = new ContextThemeWrapper(activity, R.style.SegBarStyle); final AppCompatSeekBar b = new AppCompatSeekBar(wrappedContext, null, 0); final LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT); lp.weight = 1; lp.gravity = Gravity.CENTER; b.setLayoutParams(lp); b.setTag(VOLUME_LEVEL); b.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { int progressChanged = 0; public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { progressChanged = progress; if (masterVolumeInterface != null) { masterVolumeInterface.onMasterVolumeChange(progressChanged); } } public void onStartTrackingTouch(SeekBar seekBar) { // empty } public void onStopTrackingTouch(SeekBar seekBar) { if (isAudioControlEnabled()) { activity.getStateManager().sendMessage( new MasterVolumeMsg(activity.getStateManager().getState().getActiveZone(), progressChanged)); } } }); layout.addView(b); } if (soundControl == State.SoundControlType.DEVICE_BTN_ABOVE_SLIDER) { final ReceiverInformationMsg.Zone zone = state.getActiveZoneInfo(); final int maxVolume = Math.min(getVolumeMax(state, zone), activity.getConfiguration().audioControl.getMasterVolumeMax()); layout.addView(createTextView(fragment.getContext(), VOLUME_LEVEL, State.getVolumeLevelStr(maxVolume, zone), R.style.SecondaryTextViewStyle)); } if (soundControl == State.SoundControlType.DEVICE_BTN_AROUND_SLIDER) // volume up { final MasterVolumeMsg.Command cmd = MasterVolumeMsg.Command.UP; layout.addView(fragment.createButton( cmd.getImageId(), cmd.getDescriptionId(), null, cmd)); } if (soundControl != State.SoundControlType.DEVICE_BTN_ABOVE_SLIDER) { final AudioMutingMsg.Status status = AudioMutingMsg.Status.TOGGLE; final AppCompatImageButton b = fragment.createButton( R.drawable.volume_amp_muting, status.getDescriptionId(), null, status); layout.addView(b); } } @SuppressLint("NewApi") private TextView createTextView(final Context context, @Nullable final String tag, @NonNull final String text, final int style) { final TextView tv = new TextView(context); tv.setTag(tag); tv.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { tv.setTextAppearance(style); } else { tv.setTextAppearance(context, style); } tv.setText(text); return tv; } }
25,166
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
BaseFragment.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/fragments/BaseFragment.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.fragments; import android.content.res.Configuration; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.mkulesh.onpc.MainActivity; import com.mkulesh.onpc.R; import com.mkulesh.onpc.config.CfgAppSettings; import com.mkulesh.onpc.iscp.ISCPMessage; import com.mkulesh.onpc.iscp.State; import com.mkulesh.onpc.utils.Utils; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import androidx.appcompat.view.ContextThemeWrapper; import androidx.appcompat.widget.AppCompatButton; import androidx.appcompat.widget.AppCompatImageButton; import androidx.fragment.app.Fragment; abstract public class BaseFragment extends Fragment { private boolean visibleToUser = false; MainActivity activity = null; View rootView = null; private CfgAppSettings.Tabs tabName = null; private int buttonSize = 0; int buttonMarginHorizontal = 0; private int buttonMarginVertical = 0; final PopupManager popupManager = new PopupManager(); interface ButtonListener { void onPostProcessing(); } public BaseFragment() { // Empty constructor required for fragment subclasses } void initializeFragment(LayoutInflater inflater, ViewGroup container, int layoutId, CfgAppSettings.Tabs tab) { activity = (MainActivity) getActivity(); rootView = inflater.inflate(layoutId, container, false); tabName = tab; buttonSize = activity.getResources().getDimensionPixelSize(R.dimen.button_size); buttonMarginHorizontal = activity.getResources().getDimensionPixelSize(R.dimen.button_margin_horizontal); buttonMarginVertical = activity.getResources().getDimensionPixelSize(R.dimen.button_margin_vertical); } @SuppressWarnings("SameParameterValue") void initializeFragment(LayoutInflater inflater, ViewGroup container, int layoutPort, int layoutLand, CfgAppSettings.Tabs tab) { activity = (MainActivity) getActivity(); initializeFragment(inflater, container, (activity != null && activity.orientation == Configuration.ORIENTATION_LANDSCAPE) ? layoutLand : layoutPort, tab); } @Override public void onResume() { super.onResume(); visibleToUser = true; if (activity != null) { updateContent(); } } @Override public void onPause() { super.onPause(); visibleToUser = false; } void updateContent() { update(visibleToUser && activity.isConnected() ? activity.getStateManager().getState() : null, null); } public void update(final State state, @Nullable HashSet<State.ChangeType> eventChanges) { if (eventChanges == null) { eventChanges = new HashSet<>(); Collections.addAll(eventChanges, State.ChangeType.values()); } if (state == null || !state.isOn()) { updateStandbyView(state); } else { updateActiveView(state, eventChanges); } if (activity.isConnected() && state != null) { if (state.popup.get() != null) { popupManager.showPopupDialog(activity, state); } if (!state.isPopupMode()) { popupManager.closePopupDialog(); } } } protected abstract void updateStandbyView(@Nullable final State state); protected abstract void updateActiveView(@NonNull final State state, @NonNull final HashSet<State.ChangeType> eventChanges); AppCompatImageButton createButton( @DrawableRes int imageId, @StringRes int descriptionId, final ISCPMessage msg, Object tag) { return createButton(imageId, descriptionId, msg, tag, buttonMarginHorizontal, buttonMarginHorizontal, buttonMarginVertical); } AppCompatImageButton createButton( @DrawableRes int imageId, @StringRes int descriptionId, final ISCPMessage msg, Object tag, int leftMargin, int rightMargin, int verticalMargin) { ContextThemeWrapper wrappedContext = new ContextThemeWrapper(activity, R.style.ImageButtonPrimaryStyle); final AppCompatImageButton b = new AppCompatImageButton(wrappedContext, null, 0); final LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(buttonSize, buttonSize); lp.setMargins(leftMargin, verticalMargin, rightMargin, verticalMargin); b.setLayoutParams(lp); b.setTag(tag); prepareButton(b, msg, imageId, descriptionId); return b; } void prepareButton(@NonNull AppCompatImageButton b, @DrawableRes final int imageId, @StringRes final int descriptionId) { b.setImageResource(imageId); if (descriptionId != -1) { b.setContentDescription(activity.getResources().getString(descriptionId)); } } void prepareButton(@NonNull AppCompatImageButton b, final ISCPMessage msg, @DrawableRes final int imageId, @StringRes final int descriptionId) { prepareButton(b, imageId, descriptionId); b.setImageResource(imageId); prepareButtonListeners(b, msg); setButtonEnabled(b, false); } void prepareButtonListeners(@NonNull View b, final ISCPMessage msg) { prepareButtonListeners(b, msg, null); } void prepareButtonListeners(@NonNull View b, final ISCPMessage msg, final ButtonListener listener) { b.setClickable(true); b.setOnClickListener(v -> { if (activity.isConnected() && msg != null) { activity.getStateManager().sendMessage(msg); } if (listener != null) { listener.onPostProcessing(); } }); if (b.getContentDescription() != null && b.getContentDescription().length() > 0) { b.setLongClickable(true); b.setOnLongClickListener(v -> Utils.showButtonDescription(activity, v)); } } void setButtonEnabled(View b, boolean isEnabled) { Utils.setButtonEnabled(activity, b, isEnabled); } void setButtonSelected(View b, boolean isSelected) { Utils.setButtonSelected(activity, b, isSelected); } @SuppressWarnings("SameParameterValue") AppCompatButton createButton(@StringRes int descriptionId, final ISCPMessage msg, Object tag, final ButtonListener listener) { ContextThemeWrapper wrappedContext = new ContextThemeWrapper(activity, R.style.TextButtonStyle); final AppCompatButton b = new AppCompatButton(wrappedContext, null, 0); final LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, buttonSize); lp.setMargins(buttonMarginHorizontal, 0, buttonMarginHorizontal, 0); b.setLayoutParams(lp); b.setText(descriptionId); b.setTag(tag); prepareButtonListeners(b, msg, listener); return b; } static void collectButtons(LinearLayout layout, ArrayList<View> out) { for (int k = 0; k < layout.getChildCount(); k++) { View v = layout.getChildAt(k); if (v instanceof AppCompatImageButton || v instanceof AppCompatButton) { out.add(v); } else if (v instanceof TextView && v.getTag() != null) { out.add(v); } if (v instanceof LinearLayout) { collectButtons((LinearLayout) v, out); } } } public boolean onBackPressed() { // No default processing for Back button return false; } @SuppressWarnings("WeakerAccess") @NonNull protected String getStringValue(@StringRes int descriptionId) { String value = ""; try { value = getString(descriptionId); } catch (Exception ex) { // nothing to do } return value; } public CfgAppSettings.Tabs getTabName() { return tabName; } }
9,343
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z