Blink1 mk2 Chrome connectivity via WEBUSB API Light Blink Issue - google-chrome-app

I am working on a project that need notification alert via browser using Blink(1) mk2 device.
I have tried the following code for connection to the usb using WEBUSB API.
const VENDOR_ID = 0x27b8;
navigator.usb.requestDevice({
filters: [{
vendorId: VENDOR_ID
}]
}).then(selectedDevice => {
device = selectedDevice;
console.log("open")
var tOpen = device.open();
console.log("opened")
return tOpen;
}).then(() => {
console.log("selectConfiguration")
return device.selectConfiguration(1);
}).then(() => {
console.log("claimInterface")
return device.claimInterface(0);
}).then(() => {
console.log("controlTransferOut")
const r = Math.floor((Math.random() * 255) + 0);
const g = Math.floor((Math.random() * 255) + 0);
const b = Math.floor((Math.random() * 255) + 0);
// not entirely sure what is going on below...
const fadeMillis = 500;
const th = (fadeMillis / 10) >> 8;
const tl = (fadeMillis / 10) & 0xff;
const data = new Uint8Array([0x01, 0x63, r, g, b, th, tl, 0x00, 0x00]).buffer;
var rgb = new Uint8Array(3);
rgb[0] = r;
rgb[1] = g;
rgb[2] = b;
return device.controlTransferOut({
requestType: 'standard',
recipient: 'interface',
request: 0x09,
value: 1,
index: 0
},data);
}).then(result => {
console.log(result);
}).catch(error => {
console.log(error);
});
I am able to connect to usb after setting the permissions popup. After that above code opens it, selectConfiguration, claimInterface also worked fine and when I call controlTransferOut it also sends out the command and return the result as:
USBOutTransferResult {bytesWritten: 8, status: "ok"}
But blinking or color change on the USB does not reflected.
Am I missing something or is there any other configuration I need to use in order to get the light up on USB?

I ran this code myself and found that when I set requestType to "standard" I got a "stall" but if I set it to "class" (which is correct since this is the HID class control transfer SET_REPORT) then I get "ok" and the color of the LED on my blink(1) mk2 changes.
Note, the RGB values in your snippet above are set randomly so you may be getting a very dim color.

Related

#rollup/plugin-babel cannot convert Spread operator correct when target is 'es5'

Rollup Version
rollup 2.78.0
#rollup/plugin-babel 5.3.1
Operating System (or Browser)
macOS 11.6.7
browser: chrome 107.0.5304.87
Node Version
14.18.0
rollup config
const plugins = [
nodeResolve({
preferBuiltins: false,
modulesOnly: true,
extensions: ['js', '.ts'],
}),
commonjs(),
// json(),
// globals(),
// builtins(),
typescript({
target: 'es5',
declaration: true,
declarationDir: 'dist',
}),
babel({
exclude: 'node_modules/**',
babelHelpers: 'runtime', // 开启体积优化
}),
// others
]
questions
I use Spread to convert a Set variable to Array variable, just like this:
const set = new Set();
const getSet = () => {
return [...set]
}
but I found that this function return [] all the time, so I check the build files, and found the Spread API is converted to Array.prototype.slice:
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
However, Array.prototype.slice cannot handle the Set, or in other word, Array.prototype.slice.call(Set) will return [] all the time, and it works if I set the target to es6.
expect
So, my questions is , how can it work when target is 'es5'? I think maybe I need add some configs, but I can't find a solution in document or other article

Web3: My deployment gets stuck over Test Eth Network. [Error: Failed to check for transaction receipt: with contract.deploy()]

I trying to deploy my contract using node. I am following a youtube tutorial https://www.youtube.com/watch?v=3oaJynB0nKc&list=PLzb46hGUzitDd39YzB1YvZqeIXXtmBrHX&index=26.
I'm following everything according to this tutorial but every time I run "node deploy.js", I either get timeout error: (Note I am not using any truffle framework yet.)
process["on"]("unhandledRejection", function (reason) { throw reason; });
^
Error: Failed to check for transaction receipt:
{}
at Object._fireError (C:\Users\schit\Desktop\Solidity Dapp\inbox\node_modules\web3-utils\lib\index.js:49:17)
at C:\Users\schit\Desktop\Solidity Dapp\inbox\node_modules\web3-core-method\lib\index.js:246:23
My code is as follows:
const HDWalletProvider = require('#truffle/hdwallet-provider');
const Web3 = require('web3');
const interface = require('./compile.js');
let abi = interface.abi;
let bytecode = interface.bytecode;
var mnemonic = '12-word mnemonic';
var endpoint = 'https://ropsten.infura.io/v3/<key>';
const provider = new HDWalletProvider({
mnemonic: {
phrase: mnemonic
},
providerOrUrl: endpoint
});
console.log('********DEBUG*LOG**********2');
const options = {
transactionConfirmationBlocks: 1
};
const web3 = new Web3(provider, null, options);
console.log('********DEBUG*LOG**********3')
const deploy = async () => {
const accounts = await web3.eth.getAccounts();
var balance = await web3.eth.getBalance(accounts[0]);
console.log('Account balance: ', web3.utils.fromWei(balance, "ether"));
console.log('Attempting to deploy from account', accounts[0]);
var contract = new web3.eth.Contract(abi);
**const result = await contract
.deploy({data: '0x' + bytecode, arguments: ['Hi there!']})
.send({from: accounts[0], gas: '1000000'})
.on ('error', console.error)
.on ('transactionHash', console.log)
.on ('receipt', console.log);**
console.log('Contract deployed to', result.options.address);
};
deploy();

How to run post request for multiple user in k6 performance test?

We run Get http request with multiple user(vus) and multiple iteration(iterations) for particular duration.
It is straightforward like below.
import http from 'k6/http';
import { sleep } from 'k6';
export let options ={
vus:'10',
duration: '20s',
iterations: '10'
}
export default function (){
const baseUri = 'http://Myhost:3200'
let response = http.get(`${baseUri}/api/v1/vm-inventory`)
let body = JSON.parse(response.body)
body.items.forEach(element => {
if (element.datastoreIds.length != 0 ){
console.log(JSON.stringify(element))
console.log(`Name of the vm is ${element.name}`)
}
});
sleep(1);
}
I also need to run post request by multiple user and multiple iterations. But all the example I am seeing are related to single post request. When we run multiple post request ,our data need to be changed for every iteration. How it is possible with k6? Below is my post request.
import http from 'k6/http';
import { sleep } from 'k6';
export let options ={
vus:'5',
duration: '120s',
iterations: '5'
}
let payload = `{
"VMId": "70c8b578-32ef-40d2-bcc5-81267423d2c4",
"name": "test_vm_1",
"mem": "4,
"cpu": "2",
"disk": "50gb"
}`
export default function () {
const url = 'http://myhost:3200/api/v1/vm-inventory'
var header = {
headers: {
'Content-Type': 'application/json',
},
};
let res = http.post(url, JSON.stringify(payload),header);
console.log(res.json().json.name);
sleep(5);
}
I need to change the Vm name in payload for every iteration in order the request to be unique.
How to achieve this in k6? In Jmeter , they are reading it from csv with different data for each iteration and achieving it. But I could not find any sample for K6.
we need to create the payload inside the export default function so that we can modify it there before sending it. If the VMId just needs to be a unique UUID, have a look at jslib utils library, which contains a function for generating a uuidv4:
export function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
let r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
Putting it together:
import http from 'k6/http';
import { sleep } from 'k6';
export let options = {
vus: '5',
duration: '120s',
iterations: '5'
}
export default function () {
let payload = {
VMId: uuidv4(),
name: `test_vm_${Date.now()}`,
mem: 4,
cpu: 2,
disk: "50gb"
};
const url = 'http://myhost:3200/api/v1/vm-inventory'
var header = {
headers: {
'Content-Type': 'application/json',
},
};
let res = http.post(url, JSON.stringify(payload), header);
console.log(res.json().json.name);
sleep(5);
}
export function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
let r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
(note that I've changed the payload to a JS object so that it doesn't get stringified twice).
Also we can use the payload like below.
let payload = {
VMId: uuidv4(),
name: `test_vm_vu_${__VU}`,
mem: 4,
cpu: 2,
disk: "50gb"
};
__VU will be giving virtual user number so that we can create test_vm_vu_1,test_vm_vu_3, test_vm_vu_2 . (It will be run in parallel, so the number will not come in sequential manner)
I got this answer from K6 slack community group. I post it here for anybody facing the same situation.

index.js command handler problems

I have a problem, when I debug on visual studio code, it gives me this error message "Uncaught Error: Cannot find module './command/$(files)'
Require stack:
"c:\Users\user\OneDrive\Bureau\himetsubabot\index.js"
however I put the right path and my file is called commande, here is the code
const fs = require('fs');
const Discord = require('discord.js');
const bot = new Discord.Client()
const config = require ("./config.js");
bot.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commande').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require('./commande/$(files)')
client.command.set(command.name, command)
}
bot.on("ready", async message => {
console.log("Le bot démarre")
bot.user.setStatus('online')
bot.user.setActivity("en développement")
})
bot.on('message', async (msg) => {
if(msg.content.startsWith(config.prefix) && !msg.author.bot){
cmdArray = msg.content.substring(config.prefix.length).split(" ");
cmd = cmdArray[0];
args = cmdArray.slice(1);
let command = commands.getCommand(cmd);
if(command) command.run(bot, msg, args);
if(cmd === '8ball'){}
}
})
bot.login(config.token)
Instead of using "('/commande/$(files)')" use "('./commande/${files}')".
What i mean is to use ${files} instead of $(files).

Drag and drop with touch support for react.js

How to implement drag and drop for Facebooks' react.js with support for touch events?
There's a couple of questions and articles and libraries about drag and drop for react.js, but none of them seems to mention touch events, and none of the demo's work on my phone.
In general I wonder what would be the easiest: Try to implement this using existing d&d libraries which already support touch, but may need some work to properly work together with react. Or try to use any of the react d&d examples and make them work with touch (which, seeing this issue, may not be trivial?)
react-motion (with touch events)
We have tried "react-motion" for dragging items in a list. With more than 15-20 items it becomes really laggy. (But with small list it works good, like in this demo). Be aware that mobile devices are much slower than desktops.
Important note about react-motion: Don't forget to use production mode when testing your animation's performance!
react-dnd (with touch events)
The second option was "react-dnd". It is a great library. It is low level, however, it is rather easy to understand how to work with it. But at first, "react-dnd" was not an option for us because of no touch events support.
Later, when Yahoo had released react-dnd-touch-backend we decided to switch our app from "react-motion" to "react-dnd". This solved all our performance issues. We have list 50-70 items and it just works as expected.
Yahoo has done really good work and the solution works in our production apps.
You already mentioned react-dnd and I make PR that enable dnd for touch devices so you can try it
I haven't found any answer to this yet. The accepted answer is not really an answer but it points to a github library. I am going to try to include here a complete answer using only react.
Here it goes, the code should be self explanatory, but a couple of words ahead of time. We need to use a lot of state variables to keep state between renders, otherwise any variables get reset out. To make the transitions smooth, I update the position once a render was completed using useEffect hook. I tested this in codesandbox, I'm including the link here for anybody to edit the code and play with it, just fork it. It workd with the MS Surface Book2 Pro
and Android. It has a formatting problem with the iPhone IOS. Both for Safari and Chrome. If somebody fixes it that'd be great. For now I have what I need and claim success.
Here are the files under src in codesandbox.io:
App.js
import "./styles/index.pcss";
import "./styles/tailwind-pre-build.css";
import Photos from "./Photos.js";
export default function App() {
return (
<>
<div className="flow-root bg-green-200">
<div className="my-4 bg-blue-100 mb-20">
Drag and Drop with touch screens
</div>
</div>
<div className="flow-root bg-red-200">
<div className="bg-blue-100">
<Photos />
</div>
</div>
</>
);
}
Photos.js:
import React, { useState } from "react";
import "./styles/index.pcss";
import Image from "./image";
export default function Photos() {
const [styleForNumber, setStyleForNumber] = useState({
position: "relative",
width: "58px",
height: "58px"
});
const photosArray = [
"https://spinelli.io/noderestshop/uploads/G.1natalie.1642116451444",
"https://spinelli.io/noderestshop/uploads/G.2natalie.1642116452437",
"https://spinelli.io/noderestshop/uploads/G.3natalie.1642116453418",
"https://spinelli.io/noderestshop/uploads/G.4natalie.1642116454396",
"https://spinelli.io/noderestshop/uploads/G.5natalie.1642116455384",
"https://spinelli.io/noderestshop/uploads/G.6natalie.1642116456410",
"https://spinelli.io/noderestshop/uploads/G.7natalie.1642116457466",
"https://spinelli.io/noderestshop/uploads/G.8natalie.1642116458535",
"https://spinelli.io/noderestshop/uploads/G.0natalie.1642116228246"
];
return (
<>
<div
className="w-1/2 bg-green-200"
style={{
display: "grid",
gridTemplateColumns: "[first] 60px [second] 60px [third] 60px",
gridTemplateRows: "60px 60px 60px",
rowGap: "10px",
columnGap: "20px",
position: "relative",
justifyContent: "center",
placeItems: "center"
}}
>
{photosArray.map((photo, i) => (
<div
className="relative z-1 h-full w-full flex flex-wrap content-center touch-none"
key={i}
>
<div className="contents">
<Image photo={photo} i={i} />
</div>
</div>
))}
</div>
</>
);
}
Image.js:
import React, { useRef, useState, useEffect } from "react";
import "./styles/index.pcss";
export default function Image({ photo, i }) {
const imgRef = useRef();
const [top, setTop] = useState(0);
const [left, setLeft] = useState(0);
const [drag, setDrag] = useState(false);
const [styleForImg, setStyleForImg] = useState({
position: "absolute",
width: "58px",
height: "58px"
});
const [offsetTop, setOffsetTop] = useState(-40);
const [offsetLeft, setOffsetLeft] = useState(0);
const [xAtTouchPointStart, setXAtTouchPointStart] = useState(0);
const [yAtTouchPointStart, setYAtTouchPointStart] = useState(0);
useEffect(() => {
if (drag) {
setStyleForImg({
position: "relative",
width: "58px",
height: "58px",
top: top,
left: left
});
} else {
setStyleForImg({
position: "relative",
width: "58px",
height: "58px"
});
}
console.log("style: ", styleForImg);
}, [drag, top, left]);
const handleTouchStart = (e, i) => {
e.preventDefault();
let evt = typeof e.originalEvent === "undefined" ? e : e.originalEvent;
let touch = evt.touches[0] || evt.changedTouches[0];
const x = +touch.pageX;
const y = +touch.pageY;
console.log(
"onTouchStart coordinates of icon # start: X: " + x + " | Y: " + y
);
console.log("dragged from position n = ", i + 1);
// get the mouse cursor position at startup:
setXAtTouchPointStart(x);
setYAtTouchPointStart(y);
setDrag(true);
};
const handleTouchEnd = (e) => {
// if (process.env.NODE_ENV === 'debug5' || process.env.NODE_ENV === 'development') {
e.preventDefault();
setDrag(false);
console.log(
new Date(),
"onTouchEnd event, coordinates of icon # end: X: " +
e.changedTouches[0]?.clientX +
" | Y: " +
e.changedTouches[0]?.clientY +
" | top: " +
top +
" | left: " +
left
);
};
const handleElementDrag = (e) => {
e = e || window.event;
e.preventDefault();
let x = 0;
let y = 0;
//Get touch or click position
//https://stackoverflow.com/a/41993300/5078983
if (
e.type === "touchstart" ||
e.type === "touchmove" ||
e.type === "touchend" ||
e.type === "touchcancel"
) {
let evt = typeof e.originalEvent === "undefined" ? e : e.originalEvent;
let touch = evt.touches[0] || evt.changedTouches[0];
x = +touch.pageX; // X Coordinate relative to the viewport of the touch point
y = +touch.pageY; // same for Y
} else if (
e.type === "mousedown" ||
e.type === "mouseup" ||
e.type === "mousemove" ||
e.type === "mouseover" ||
e.type === "mouseout" ||
e.type === "mouseenter" ||
e.type === "mouseleave"
) {
x = +e.clientX;
y = +e.clientY;
}
console.log("x: ", x, "y: ", y);
// calculate the new cursor position:
const xRelativeToStart = x - xAtTouchPointStart;
console.log(
"xRel = ",
x,
" - ",
xAtTouchPointStart,
" = ",
xRelativeToStart
);
const yRelativeToStart = y - yAtTouchPointStart;
console.log(
"yRel = ",
y,
" - ",
yAtTouchPointStart,
" = ",
yRelativeToStart
);
// setXAtTouchPointStart(x); // Reseting relative point to current touch point
// setYAtTouchPointStart(y);
// set the element's new position:
setTop(yRelativeToStart + "px");
setLeft(xRelativeToStart + "px");
console.log("top: ", yRelativeToStart + "px");
console.log("Left: ", xRelativeToStart + "px");
};
const handleDragEnd = (e) => {
// if (process.env.NODE_ENV === 'debug5' || process.env.NODE_ENV === 'development') {
console.log(
new Date(),
"Coordinates of icon # end X: " + e.clientX + " | Y: " + e.clientY
);
};
const handleDragStart = (e, i) => {
// From https://stackoverflow.com/a/69109382/15355839
e.stopPropagation(); // let child take the drag
e.dataTransfer.dropEffect = "move";
e.dataTransfer.effectAllowed = "move";
console.log(
"Coordinates of icon # start: X: " + e.clientX + " | Y: " + e.clientY
);
// console.log ('event: ', e)
console.log("dragged from position n = ", i + 1);
};
return (
<img
ref={imgRef}
className="hover:border-none border-4 border-solid border-green-600 mb-4"
src={photo}
alt="placeholder"
style={styleForImg}
onDragStart={(e) => handleDragStart(e, i)}
onDragEnd={handleDragEnd}
onTouchStart={(e) => handleTouchStart(e, i)}
onTouchEnd={handleTouchEnd}
onTouchMove={handleElementDrag}
></img>
);
}
index.js:
import { StrictMode } from "react";
import ReactDOM from "react-dom";
import "./styles/index.pcss";
import App from "./App";
const root = document.getElementById("root");
ReactDOM.render(
<StrictMode>
<App />
</StrictMode>,
root
);
styles.css:
.Main {
font-family: sans-serif;
text-align: center;
}
/styles/index.pcss:
#tailwind base;
#tailwind components;
#tailwind utilities;
I couldn't make tailwinds grid work, so I used the actual css inline styles. No idea why they didn't in codesandbox.