* @brief Implements deviceWrite(data, sourceId?) for the JS scripting engine. */
| 139 | * @brief Implements deviceWrite(data, sourceId?) for the JS scripting engine. |
| 140 | */ |
| 141 | QVariantMap DataModel::DeviceWriteBridge::write(const QJSValue& data, const QJSValue& sourceIdVal) |
| 142 | { |
| 143 | auto makeError = [](const QString& msg) -> QVariantMap { |
| 144 | QVariantMap m; |
| 145 | m.insert(QStringLiteral("ok"), false); |
| 146 | m.insert(QStringLiteral("error"), msg); |
| 147 | return m; |
| 148 | }; |
| 149 | |
| 150 | int sourceId = defaultSourceId; |
| 151 | if (!sourceIdVal.isUndefined() && !sourceIdVal.isNull()) { |
| 152 | if (!sourceIdVal.isNumber()) |
| 153 | return makeError(QStringLiteral("deviceWrite: sourceId must be a number")); |
| 154 | |
| 155 | sourceId = static_cast<int>(sourceIdVal.toInt()); |
| 156 | } |
| 157 | |
| 158 | QByteArray bytes; |
| 159 | if (data.isString()) { |
| 160 | bytes = data.toString().toUtf8(); |
| 161 | } else if (data.isArray()) { |
| 162 | const int len = data.property(QStringLiteral("length")).toInt(); |
| 163 | bytes.reserve(len); |
| 164 | for (int i = 0; i < len; ++i) |
| 165 | bytes.append(static_cast<char>(data.property(static_cast<quint32>(i)).toInt() & 0xff)); |
| 166 | } else { |
| 167 | return makeError(QStringLiteral("deviceWrite: data must be a string or byte array")); |
| 168 | } |
| 169 | |
| 170 | if (bytes.isEmpty()) |
| 171 | return makeError(QStringLiteral("deviceWrite: data is empty")); |
| 172 | |
| 173 | QString errorMsg; |
| 174 | const qint64 written = performDeviceWrite(sourceId, bytes, errorMsg); |
| 175 | |
| 176 | QVariantMap result; |
| 177 | if (written > 0 && errorMsg.isEmpty()) { |
| 178 | result.insert(QStringLiteral("ok"), true); |
| 179 | } else { |
| 180 | result.insert(QStringLiteral("ok"), false); |
| 181 | result.insert(QStringLiteral("error"), errorMsg); |
| 182 | } |
| 183 | return result; |
| 184 | } |
| 185 | |
| 186 | //-------------------------------------------------------------------------------------------------- |
| 187 | // Public installation entry points |
no test coverage detected