Redirect According To Device - node.js

In Node I am trying to send response according to device. If it is Web I am sending one kind of respone and If it is Mobile I am sending another kind of response. But I don't know how to find the device and implement condition.
TS
if(mobile){ //How to check whether it is mobile
res.send(res.mobile)
}
else if(web){ //How to check whether it is web
res.send(res.web)
}
else{
res.send(res.error)
}

You can use npm install node-device-detector --production
const DeviceDetector = require('node-device-detector');
const DeviceHelper = require('node-device-detector/helpers');
const detector = new DeviceDetector;
const userAgent = 'Mozilla/5.0 (Linux; Android 5.0; NX505J Build/KVT49L) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.78 Mobile Safari/537.36';
const result = detector.detect(userAgent);
/* check device type (feature phone, smartphone or phablet) */
DeviceHelper.isMobile(result);
/* check device type is desktop */
DeviceHelper.isDesktop(result);
/* check device type is tablet */
DeviceHelper.isTabled(result);
/* check device type car (side panel in car) */
DeviceHelper.isCar(result);
/* check device type feature phone (push-button telephones) */
DeviceHelper.isFeaturePhone(result);
/* check device type smartphone */
DeviceHelper.isSmartphone(result);
/* check device type phablet */
DeviceHelper.isPhablet(result);
/* check device type game console (xBox, PlayStation, Nintendo etc) */
DeviceHelper.isConsole(result);
/* check device type smart speaker (Alisa, Alexa, HomePod etc) */
DeviceHelper.isSmartSpeaker(result);
/* check device type SmartTV/TV box */
DeviceHelper.isTv(result);
/* check device type portable camera */
DeviceHelper.isCamera(result);
/* portable terminal, portable projector */
DeviceHelper.isPeripheral(result);
/* */
DeviceHelper.isSmartDisplay(result);
/* check device type boxes, blu-ray players */
DeviceHelper.isPortableMediaPlayer(result);
/* check device type watches, headsets */
DeviceHelper.isWearable(result);
Replace userAgent with your Header : req.headers['user-agent'].
More example https://www.npmjs.com/package/node-device-detector

Related

Open Cash Drawer via WebUSB JavaScript

I have a c# application that can open a cash drawer with the Windows Driver Installed. Pretty simple as the driver makes the USB device appears as a serial port:
SerialPort rsPort = new SerialPort(textBox1.Text);
byte[] openCmd = new byte[5];
openCmd[0] = 27;
openCmd[1] = 112;
openCmd[2] = 0;
openCmd[3] = 60;
openCmd[4] = 255;
rsPort.Open();
Thread.Sleep(100);
rsPort.Write(openCmd, 0, 5);
Thread.Sleep(100);
rsPort.Close();
I'm now trying to open the same USB cash Drawer via WebUSB. I've used ZaDig to install a generic USB drive and Chrome can see the USB device; can open the device; however, i'm struggling to send the correct commands.
Here is an image of the config:
Here is my current code:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript WebUSB</h2>
<button id="myBtn">Try it</button>
<script>
document.getElementById("myBtn").addEventListener("click", talkToDrawer);
async function talkToDrawer() {
try {
let device = await navigator.usb.requestDevice({ filters: [{ vendorId: 1659 }] });
console.log(device);
await device.open(); // Begin a session.
await device.selectConfiguration(1); // Select configuration #1 for the device.
await device.claimInterface(0); // Request exclusive control over interface #2.
result = await device.controlTransferOut({
requestType: 'standard', // tried all combinations: standard / class / vendor
recipient: 'endpoint', // tried all combinations: device / interface / endpoint / other
request: 0x27,
value: 0,
index: 1
});
result = await device.controlTransferOut({
requestType: 'standard', // tried all combinations: standard / class / vendor
recipient: 'endpoint', // tried all combinations: device / interface / endpoint / other
request: 0x112,
value: 0,
index: 1
});
result = await device.controlTransferOut({
requestType: 'standard', // tried all combinations: standard / class / vendor
recipient: 'endpoint', // tried all combinations: device / interface / endpoint / other
request: 0x0,
value: 0,
index: 1
});
result = await device.controlTransferOut({
requestType: 'standard', // tried all combinations: standard / class / vendor
recipient: 'endpoint', // tried all combinations: device / interface / endpoint / other
request: 0x60,
value: 0,
index: 1
});
result = await device.controlTransferOut({
requestType: 'standard', // tried all combinations: standard / class / vendor
recipient: 'endpoint', // tried all combinations: device / interface / endpoint / other
request: 0x255,
value: 0,
index: 1
});
} catch (error) {
console.log(error);
}
}
</script>
</body>
</html>
Without knowing more about the device there are two errors I see in the code,
In the C# example the command is [27, 112, 0, 60, 255] with the values given in decimal while in the Javascript example the values are given as hexadecimal constants. The appropriate code for constructing the command buffer in Javascript is,
const cmd = new Uint8Array([27, 112, 0, 60, 255]);
Rather than using controlTransferOut() to send the data it is most likely correct to use transferOut() and select endpoint number 3. The Prolific USB-to-serial converter chips implement a protocol similar to the standard USB serial class, which uses a pair of bulk IN and OUT endpoints for the serial data stream,
result = await device.transferOut(3, cmd);
The remaining open question is whether you need to perform any control transfers before you can send this command. Control transfers are used to configure the device and for a USB-to-serial chip this usually involves things like setting baud rate or setting the DCE bit high. When reverse-engineering how to communicate with a USB device I recommend using Wireshark to view the USB traffic from a working driver.
Note, that if you are working with a serial device you should take a the Serial API. There is an experimental implementation available in Chrome behind the chrome://flags/#enable-experimental-web-platform-features flag. This API is designed for applications specifically targeting serial devices and avoids having to re-implement the driver for the USB-to-serial chip.

UWP How to check incoming requests from BLE device?

How to check all incoming requests from paired BLE device to current device?
I think it possible with Events, maybe UWP have needle event, or i must implement custom event, but where is the right way?
Microsoft have explainations about GATT Server, i think it's not what i need, 'cause i don't need a server with services and characteristics, i need only check incoming request and parse passed data in my application.
I'm not found sure way for checking incoming requests, but i make some trick.
Application can subscribe for notifications from device (in my case it's Mi Band 2) and receive some data from this device across ValueChanged.
One time i call ValueChanged handler in App.xaml.cs after connecting and pairing device and this working on all application, i don't need call it again and again.
Here is App.xaml.cs part of code.
protected async override void OnLaunched(LaunchActivatedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
MiBand2SDK.MiBand2 band = new MiBand2SDK.MiBand2();
var page = typeof(Views.AuthPage);
// Checking for device availability and current session
if (_LocalSettings.Values["isAuthorized"] != null
&& await band.ConnectAsync())
{
if (e.PreviousExecutionState == ApplicationExecutionState.NotRunning && await band.Auth.AuthenticateAsync())
page = typeof(Views.MainPage);
else if (band.Auth.IsAuthenticated())
page = typeof(Views.MainPage);
// Here we are, this notification handler of responses from the band.
band.HeartRate.SetNotificationHandler();
}
else
{
System.Diagnostics.Debug.WriteLine("Not Authenticated...");
}
// other part of code...
Here is HeartRate.SetNotificationHandler() code:
public async void SetNotificationHandler()
{
_heartRateMeasurementCharacteristic = await Gatt.GetCharacteristicByServiceUuid(HEART_RATE_SERVICE, HEART_RATE_MEASUREMENT_CHARACTERISTIC);
Debug.WriteLine("Subscribe for HeartRate notifications from band...");
if (await _heartRateMeasurementCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify) == GattCommunicationStatus.Success)
// Just subscribe for notifications and set ValueChanged. It's all.
_heartRateMeasurementCharacteristic.ValueChanged += HeartRateMeasurementCharacteristicValueChanged;
}
Hope it helps someone...

How to Connect IoT device to the remote monitoring preconfigured solution (Windows)? How to implement and specify the behaviour of IoT hub device?

https://learn.microsoft.com/en-us/azure/iot-suite/iot-suite-connecting-devices#create-a-c-sample-solution-on-windows
Add the following functions that execute when the device receives the SetTemperature and SetHumidity commands from IoT Hub:
EXECUTE_COMMAND_RESULT SetTemperature(Thermostat* thermostat, int temperature)
{
(void)printf("Received temperature %d\r\n", temperature);
thermostat->Temperature = temperature;
return EXECUTE_COMMAND_SUCCESS;
}
EXECUTE_COMMAND_RESULT SetHumidity(Thermostat* thermostat, int humidity)
{
(void)printf("Received humidity %d\r\n", humidity);
thermostat->Humidity = humidity;
return EXECUTE_COMMAND_SUCCESS;
}
Add the following function that sends a message to IoT Hub:
static void sendMessage(IOTHUB_CLIENT_HANDLE iotHubClientHandle, const unsigned char* buffer, size_t size)
{
IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(buffer, size);
if (messageHandle == NULL)
{
printf("unable to create a new IoTHubMessage\r\n");
}
else
{
if (IoTHubClient_SendEventAsync(iotHubClientHandle, messageHandle, NULL, NULL) != IOTHUB_CLIENT_OK)
{
printf("failed to hand over the message to IoTHubClient");
}
else
{
printf("IoTHubClient accepted the message for delivery\r\n");
}
IoTHubMessage_Destroy(messageHandle);
}
free((void*)buffer);
}
More in given link
The article you're referring to here shows you how to build and run this sample code on a Windows desktop machine using Visual Studio. There are two other equivalent articles that show you how to run the same code on a Linux machine or an mbed device.
If you want to follow an in-depth tutorial on how to use another hardware device such as a Raspberry Pi or Intel Edison with Azure IoT Hub, then take a look at the collection of IoT Hub tutorials in the Get started folder here.

NFC Tag not working on Gear S2

Im trying to read the data in NFC tag using web development. I am able to detect tags from emulator, but on Gear S2 it does not work.
I have given all the privileges in config.xml
<tizen:privilege name="http://tizen.org/privilege/nfc.common"/>
<tizen:privilege name="http://tizen.org/privilege/nfc.tag"/>
<tizen:privilege name="http://tizen.org/privilege/bluetooth.admin"/>
<tizen:privilege name="http://tizen.org/privilege/nfc.admin"/>
<tizen:privilege name="http://tizen.org/privilege/nfc.cardemulation"/>
I am using whiztags NFC tags with Gear S2, they are working with my mobile(Nexus 5).
I have switched on the NFC in my watch, but still they don't respond to tags.
Code:
var adapter = tizen.nfc.getDefaultAdapter();
adapter.setPowered(
true, // Enable NFC adapter
function () {console.log('Power on success');}, // Handle succes
function () {console.log('Power on failed');}); // Handle failure
//
var onSuccessCB = {onattach : function(nfcTag) {
console.log("NFC Tag's type is " + nfcTag.type);
navigator.vibrate([600, 100, 300, 200, 0]);
for(var i in nfcTag.properties) {
console.log("key:" + i + " value:" + nfcTag.properties[i]);
}
}, ondetach : function() {
console.log("NFC Tag is detached");
}};
adapter.setTagListener(onSuccessCB);
The NFC API is optional for both Tizen mobile and wearable profiles, which means that it may not be supported in all mobile and wearable devices. The NFC API is supported on the Tizen wearable Emulator, but not on the Tizen mobile Emulator.
Please go through this link for more details.
I've seen some other people having same issue. Have a look on this link too.

New websocket on different instance of site

I have a remote control for 4 Devices running on a node server.
Each device has its own page (/1, /2, /3, /4), but they are all generated from the same html/js.
the only difference is the ip for each device, loaded from a json on the server depending on the url path.
This all works, but the problem is: i have 3 obviously wrong IPs entered for testing purposes, and one correct one. Now if i open the correct one, go back to the parent page and open the page of a device with a wrong IP, it is still shown as online and can be controlled.
I understand this like: the socket stays open across the pages and is actually not built new on every site.
how can i make sure that each subpage generates a new socket?
right now, i just have
socket = new io.connect();
in the browser.js,
ioServer.on('connection', function (socket) {
//etc.
}
in the app.js and it works for ONE device.
Am I right to assume that I need some kind of "destroy socket if page is changed"-function?
Thanks for the help
By the looks of it, you only want to instantiate and boot a device when the device's client connects for the first time and emits 'startup'. If this is not the case, I'd probably instantiate and boot each device when the server starts.
Going with the first case, I'd store your devices in a key-value object and reuse them when needed.
var devices = {};
ioServer.on('connection', function (socket) {
var client_ip_address = socket.request.connection.remoteAddress;
console.log("New Connection from: " + client_ip_address);
var device;
socket.on('startup', function (data) {
var deviceId = data.device;
console.log("[INFO] startup: device " + deviceId);
//If this device is already in devices, resuse it
if (deviceId in devices) {
//Get the device from your devices object
device = devices[deviceId];
//Otherwise, create a new device and store it in devices
} else {
device = new HyperDeck(deviceId);
//Store new device in devices object
devices[deviceId] = device;
device.boot();
}
console.log(device.id);
console.log(device.ip);
});
...

Resources