Cactus
Cactus

Reputation: 87

Sending TCP packets over IP in React Native not working

I have been trying to send TCP hex packets over IP with the use of the react-native-tcp library. I have coded a very, very simple app that tries to do this. However, the function sendPackets in the code never seems to run. I think it may be an issue with my implementation of the onPress method in the button, however I cannot rule out the possibility that my sendPackets function is coded incorrectly.

Here is the code for the app

import React, { useState } from "react";
import {
  View,
  Text,
  TextInput,
  Button,
  SafeAreaView,
  StyleSheet,
  TouchableOpacity,
} from "react-native";
import TcpSocket from "react-native-tcp";
import { Buffer } from "buffer";

const sendPacket = () => {
  console.log("sendPacket called");
  try {
    const packet = Buffer.from(
      "0x038, 0x031, 0x020, 0x030, 0x031, 0x020, 0x030, 0x036, 0x020, 0x030, 0x031, 0x020, 0x030, 0x032, 0x020, 0x030, 0x032, 0x020, 0x030, 0x031, 0x020, 0x030, 0x033, 0x020, 0x066, 0x066",
      "hex"
    );
    const client = TcpSocket.createConnection({
      port: 5678,
      host: "Ipaddr",
    });

    client.write(packet);
  } catch (error) {
    console.log(error);
  }
};

const App = () => {
  console.log("app called");

  return (
    <SafeAreaView>
      <View>
        {console.log("button Rendered")}
        <TouchableOpacity onPress={sendPacket}>
          <Text>Send Packet</Text>
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
};

export default App;

In case it is useful: This code is for controlling a PTZ camera over IP using the sony VISCA protocol. It sends the command 81 01 06 01 VV WW 01 03 FF where V varies between 0x01 and 0x18 (controls speed of camera pan). W varies between 0x01 and 0x14 (controls tilt speed of camera)

Upvotes: 3

Views: 728

Answers (1)

nCr78
nCr78

Reputation: 480

The first thing I noticed is that you haven't added the second argument to TcpSocket.createConnection() which should be something like:

const options = { port: 5678, host: "Ipaddr" };
const client = TcpSocket.createConnection(options, () => {
    client.write(packet);
});

Hope this helps!

Upvotes: 1

Related Questions