I am a bit out of my comfort zone here, so looking for a bit of guidance. I am trying to access an api to display live metrics, using phonic-elixir (https://www.npmjs.com/package/phoenix-elixir) - am just sort of trying to get it running first, so have loaded up their example code and connecting to an api (forgive me if the terminology is all wrong, I am new at this!)
This is my code:
import {Socket} from 'phoenix-elixir';
let socket = new Socket('ws://API_URL_HERE', {params: {'auth-token': 'AUTH_TOKEN'}})
socket.connect()
let channel = socket.channel('updates:new', {})
channel.join()
.receive('ok', resp => { console.log('Joined successfully', resp) })
.receive('error', resp => { console.log('Unable to join', resp) })
channel.on('update', payload => {
console.log('Received: ' + payload);
console.log(payload);
})
export default socket
When I run babel index.js | node I am getting the error: this.transport = opts.transport || window.WebSocket || LongPoll; and ReferenceError: window is not defined
Just some advice to point me in the right direction would be fantastic. Is window not defined because it needs a dom? Do I need a server to run this in?
Thank you :)
I just ported the client to be compatible with node.JS.
Here is the link https://github.com/mcampa/phoenix-channels
The difference with the original client is that this does not use long-polling and you need to pass the absolute url instead of the relative url.
To install it run:
npm install --save phoenix-channels
Same API as the original:
const { Socket } = require('phoenix-channels')
let socket = new Socket("ws://example.com/socket")
socket.connect()
// Now that you are connected, you can join channels with a topic:
let channel = socket.channel("room:lobby", {})
channel.join()
.receive("ok", resp => { console.log("Joined successfully", resp) })
.receive("error", resp => { console.log("Unable to join", resp) })
phoenix-elixir is client-side library that is supposed to be used in browsers not in node environment. You should create html page with your code and open it in browser to test it out.
Related
I am using analytics.js to make a custom tracking over my website. As I wish to send the hit to PubSub, I used this documentation (Node.JS tab) to connect my TypeScript code to PubSub (not perfect I know. I am trying to make it work before cleaning).
ga(() => {
ga("set", "cookieExpires", 0);
const tracker = ga.getByName(trackerName);
tracker.set("sendHitTask", (model: any) => {
var refusedParam = ["_gid", "tid"];
let hit = model.get("hitPayload").split("&").filter((paramValue: string) => {
let param = paramValue.split("=")[0];
return (refusedParam.indexOf(param) == -1);
}).join("&");
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
const topicNameOrId = 'tracking-test';
const data = JSON.stringify(hit);
// Creates a client; cache this for further use
const pubSubClient = new PubSub();
console.log("DATA IS " + data);
async function publishMessage() {
// Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject)
const dataBuffer = Buffer.from(data);
try {
const messageId = await pubSubClient
.topic(topicNameOrId)
.publishMessage({data: dataBuffer});
console.log(`Message ${messageId} published.`);
} catch (error) {
console.error(`Received error while publishing: ${error.message}`);
process.exitCode = 1;
}
}
publishMessage();
});
});
I don't have any error when building and running this code. But, when I locally connect to my website, I have the following error inside the JS console Uncaught TypeError: a.grpc is undefined.
I tried to put grpc inside my package.json, but no success at removing the error and having a correct behavior.
Did I miss something ? How can I use analytics.js, and send data directly to PubSub ?
I want to connect a Solana wallet (phantom or any other) to a web application through the web3js library. I've read docs for most wallets and it seems like it's just as simple as await window.solana.request({ method: "connect" }); but window.solana is undefined in my case.
When I do console.log(window) I can see the Solana value with all its corresponding keys and values.
How can I do this?
I've found a working code that solved my issue. I am not sure what was the issue as I'm not very experienced with js, but the following code lets me connect to phantom.
I found this on StackOverflow on a similar thread, although I belive the original answer is missing some brackets.
Solana : Adding Sollet / Phantom Wallet Connect to my website - Steps?
const getProvider = async () => {
if ("solana" in window) {
await window.solana.connect(); // opens wallet to connect to
const provider = window.solana;
if (provider.isPhantom) {
console.log("Is Phantom installed? ", provider.isPhantom);
return provider;
}
} else {
document.write('Install https://www.phantom.app/');
}
};
window.onload = () => {
getProvider().then(provider => {
console.log('key', provider.publicKey.toString())
})
.catch(function(error){
console.log(error)
});
}
With your current implementation, everytime you refresh the app, you will get pop up to connect to the wallet. Instead you add {onlyIfTrusted:true} option to connect.
const getProvider = async () => {
if ("solana" in window) {
await window.solana.connect({onlyIfTrusted:true}); // opens wallet to connect to
const provider = window.solana;
if (provider.isPhantom) {
console.log("Is Phantom installed? ", provider.isPhantom);
return provider;
}
} else {
document.write('Install https://www.phantom.app/');
}
};
then instead of getting pop up when you reload the app, write a connection function to handle the connection when a user clicks on the button
const connectToWallet=async ()=>{
const {solana}=window
if(solana){
const response=await solana.connect()
console.log('address',response.publicKey.toString())
}
}
<button onClick={connectToWallet} >
Connect to Wallet
</button>
Now once user is connected, when you reload the app, it you wont get pop up to connect to the wallet
Is your website https enabled? If not then it won't work
I'm trying to use peerjs to connect an host with a client. I have two files (one for the host, one for the client). The host will generate a peerId which the client is using to connect to him. It's basically the tutorial from here.
host.html
const peer = new Peer()
peer.on('open', () => {
console.log('ID: ' + peer.id)
})
peer.on('connection', (conn) => {
conn.on('data', (data) => {
// Will print 'hi!'
console.log(data)
})
conn.on('open', () => {
conn.send('hello!')
})
})
<script src="https://unpkg.com/peerjs#1.3.1/dist/peerjs.min.js"></script>
client.html
const peer = new Peer()
const conn = peer.connect('1781a113-d095-4be5-9969-b80d9c364f6b')
conn.on('open', () => {
conn.send('hi!')
})
<script src="https://unpkg.com/peerjs#1.3.1/dist/peerjs.min.js"></script>
The client is not connecting nor sending messages. I tried to use their example to connect to my host and this was working. I was able to send messages to the host. What is the issue with my client?
It's a little vague in the documentation, but if you don't wait on the open event, messages to the server will be queued. I'm not sure if there is additional configuration needed to enable queuing, but simply waiting on the open event should work in your case
const peer = new Peer()
peer.on('open', () => {
const conn = peer.connect('1781a113-d095-4be5-9969-b80d9c364f6b')
conn.on('open', () => {
conn.send('hi!')
})
})
Keep in mind that the peer id generated in your 'host' will change every time you refresh the browser, so you might want to pick your own id instead of getting a random one
I am able to make a BLE connection with the hardware. By using service UUID and characteristics UUID I am able to receive data from the hardware through start notification function. But when I try to send data to the hardware its showing error [Write error status-3] as shown in the below code.
BleManager.retrieveServices(peripheral.id).then((peripheralInfo) => {
console.log(peripheralInfo);
var service = '6e400001-b5a3-f393-e0a9-e50e24dcca9e';
var WriteCharacteristic = '6e400002-b5a3-f393-e0a9-e50e24dcca9e';
var ReadCharacteristic = '6e400003-b5a3-f393-e0a9-e50e24dcca9e';
setTimeout(() => {
// receiving data from hardware
BleManager.startNotification(peripheral.id, service, ReadCharacteristic).then(() => {
console.log('Started notification on ' + peripheral.id);
setTimeout(() => {
// sending data to the hardware
BleManager.write(peripheral.id, service, WriteCharacteristic, [1,95]).then(() => {
console.log('Writed NORMAL crust');
});
}, 500);
}).catch((error) => {
console.log('Notification error', error);
});
First faced some problems with characteristics not found. After some changes, I am getting error as
Write error Status - 3
I am not able to find any solution for this error.
Thank you in advance
While using BleManager.write, you should first prepare your data
Data preparation:
If your data is not in byte array format you should convert it first. For strings you can use convert-string or other npm package in order to achieve that. Install the package first:
npm install convert-string
Then use it in your application:
// Import/require in the beginning of the file
import { stringToBytes } from "convert-string";
// Convert data to byte array before write/writeWithoutResponse
const data = stringToBytes(yourStringData);
In my case I converted my data to byte format, this way and you can do the same.
const dataByte = convertString.UTF8.stringToBytes(data);
Then used in my code
BleManager.retrieveServices(currentDevice.PID).then((peripheralInfo) => {
console.log(peripheralInfo);
BleManager.write(
currentDevice.PID,
'0000ffe0-0000-1000-8000-00805f9b34fb',
'0000ffe1-0000-1000-8000-00805f9b34fb',
dataByte,
)
.then(() => {
console.log(`Sent ${dataByte}`);
})
.catch((error) => {
console.log(error);
});
});
};
So im trying to make an update checker that doesnt actually download the update but nvm and all im trying to is check if the version on the package.json on github is the same as the one in the app (im making it in electron)
And with this code i get a "path must be a string error" (heres an image https://gyazo.com/7b55a1cbe96b2719bb588a6591855839 )
also i did look it up many times and in fact the code to get the package.json from github with the http module was from how to require from URL in Node.js
function checkforupdate() {
var http = require('http')
const file_url = "https://raw.githubusercontent.com/FloffahDevelopments/FloffahsHub/master/package.json";
const oldpackagejson = require("package.json");
document.getElementById("checkupdate").innerHTML = 'Checking for updates</br>Please wait</br><img src="./assets/icons/gif/loading.gif" alt="loading" style="width: 10%; left: 45%;">'
http.get(file_url).then(res => res.json()).then(pack => {
if (pack.version !== oldpackagejson.version) {
document.getElementById("checkupdate").innerHTML = 'Update available!'
} else {
document.getElementById("checkupdate").innerHTML = 'No update available!'
}
});
}
This will make the request you want:
var https = require('https')
const file_url = "https://raw.githubusercontent.com/FloffahDevelopments/FloffahsHub/master/package.json"
const oldpackagejson = require("./package.json");
https.get(file_url, (res) => {
res.on('data', (d) => {
process.stdout.write(d)
})
}).on('error', (e) => {
console.log(e)
})
Some mistakes you made were: Treating http.get as a promise when it's not. It could by with the inclusion of a module like bluebird, though. You used the http module to make an https request. You did not give http.get it's parameters correctly, that is, your syntax was incorrect. You're trying to update the DOM on server-side code, you should separate client and server logic. res => res.json() does not change res to json, you'll need JSON.parse.