unity udp dgram socket not working on hololens - hololens

I tried to connect between hololens and python server. So I used dgram socket but this is not working on hololens.
this is my code sample.
hololens client
public string conHost = "192.168.0.58";
public int conPort = 3174;
void Start()
{
ipep = new IPEndPoint(IPAddress.Parse(conHost), conPort);
clientThread = new Thread(setupSocket);
clientThread.Start();
}
public void setupSocket()
{
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
}
void Update()
{
if(Send)
{
Send = false;
byte[] bytes = Encoding.UTF8.GetBytes("124306324602435");
byte[] buffer = Encoding.UTF8.GetBytes(bytes.Length.ToString());
mySocket.SendTo(buffer, buffer.Length, SocketFlags.None, ipep);
}
}
python server
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#server_address = "192.168.0.18", 9029
#print('starting up on {} port {}'.format(*server_address))
sock.bind(("192.168.0.58", 3174))
ready=True
while(ready):
try:
epoch_time = time.time()
data,address = sock.recvfrom(100)
fileLength = data.decode("utf-8")
print(fileLength)
except:
continue
When I play this code in unity project, it works. But in hololens, not working.
I used try-catch, I got this error messege on Update
System.NullReferenceException: Object reference not set to an instance of an object [0x00000] in <000000000000000000000000000000000>:0

It occurs because the variable mySocket is not initialized as an expected value. Actually, the implementation of System.Threading has changed in .NET 4.x in a way that is not backward compatible, and the HoloLens app uses IL2CPP scripting backend with.NET4.x but the Unity Editor uses Mono scripting backend with.NET2.x. So, it works in Unity Editor but fails to start your thread in .NET4.x, we recommended that using System.Threading.Tasks class instead. Besides, to use WinRT APIs in Unity projects built for the UWP you need to use preprocessor directives, more information please see:WinRT APIs with Unity for HoloLens

Related

Groovy code to read rabbitMQ working on Windows, not working on Linux

Need: Read from rabbitMQ with AMQPS
Problem: ConsumeAMQP is not working so I'm using groovy script that's working on windows and not working on linux. Error message is:
groovy.lang.MissingMethodException: No signature of method: com.rabbitmq.client.ConnectionFactory.setUri() is applicable for argument types: (String) values: [amqps://user:xxxxxxxXXXxxxx#c-s565c7-ag77-etc-etc-etc.mq.us-east-1.amazonaws.com:5671/virtualhost]
Possible solutions: getAt(java.lang.String), every(), every(groovy.lang.Closure)
Troubleshooting:
Developed code on python to test from my machine using pika lib and it's working with URL amqps. It reads from rabbitMQ. no connection issues.
put the python code on the nifi server (1.15.3) machine, installed python and pika lib, execute on the command line, it's working on the server and reads from rabbitMQ.
Develop groovy code to test from my windows apache nifi (1.15.3)` and it's working, it's reading from rabbitMQ client system.
Copy the code (copy past) to the nifi server, uploaded the .jar lib also. Not working with this error message. create a groovy file and execute the code. not working.
Can anyone help me?
NOTE: I want to use groovy code to output the results to the flowfile.
#Grab('com.rabbitmq:amqp-client:5.14.2')
import com.rabbitmq.client.*
import org.apache.commons.io.IOUtils
import java.nio.charset.*
// -- Define connection
def ConnectionFactory factory = new ConnectionFactory();
factory.setUri('amqps://user:password#a-r5t60-etc-etc-etc.mq.us-east-1.amazonaws.com:5671/virtualhost');
factory.useSslProtocol();
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
// -- Waiting for messages.");
boolean noAck = false;
int count = 0;
while(count<10) {
GetResponse response = channel.basicGet("db-user-q" , noAck)
if (response != null) {
byte[] body = response.getBody()
long deliveryTag = response.getEnvelope().getDeliveryTag()
def msg = new String(body, "UTF-8")
channel.basicAck(response.envelope.deliveryTag, false)
def flowFile = session.create()
flowFile = session.putAttribute(flowFile, 'myAttr', msg)
session.transfer(flowFile, REL_SUCCESS);
}
count++;
}
channel.close();
connection.close();
The following code is suspect:
def ConnectionFactory factory = new ConnectionFactory();
You don't need both def and a type ConnectionFactory. Just change it to this:
ConnectionFactory factory = new ConnectionFactory()
You don't need the semi-colon either. The keyword def is used for dynamic typing situations (or laziness), and specifying the type (ie ConnectionFactory) is for static typing situations. You can't have both. It's either dynamic or static typing. I suspect Groovy VM is confused by what type the object is hence why it can't figure out if setUri exists or not.

How to use LibvlcSharp on Linux?

I'm trying to use LibvlcSharp on a linux installation (Ubuntu 18.04). I'm following all the instructions, including this one Getting started on LibVLCSharp.Gtk for Linux but my application always crash. It's working perfectly on windows, because there we can add VideoLAN.LibVLC.Windows package, but I couldn't find someting similar for Linux.
My code:
static void Main(string[] args)
{
// Record in a file "record.ts" located in the bin folder next to the app
var currentDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var destination = Path.Combine(currentDirectory, "record.ts");
// Load native libvlc library
Core.Initialize();
using (var libvlc = new LibVLC())
//var libvlc = "/usr/lib/x86_64-linux-gnu/";
using (var mediaPlayer = new MediaPlayer(libvlc))
{
// Redirect log output to the console
libvlc.Log += (sender, e) => Console.WriteLine($"[{e.Level}] {e.Module}:{e.Message}");
// Create new media with HLS link
var urlRadio = "http://transamerica.crossradio.com.br:9126/live.mp3";
var media = new Media(libvlc, urlRadio, FromType.FromLocation);
// Define stream output options.
// In this case stream to a file with the given path and play locally the stream while streaming it.
media.AddOption(":sout=#file{dst=" + destination + "}");
media.AddOption(":sout-keep");
// Start recording
mediaPlayer.Play(media);
Console.WriteLine($"Recording in {destination}");
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}
The error message:
Unhandled Exception: LibVLCSharp.Shared.VLCException: Failed to perform instanciation on the native side. Make sure you installed the correct VideoLAN.LibVLC.[YourPlatform] package in your platform specific project
at LibVLCSharp.Shared.Internal..ctor(Func1 create, Action1 release)
at RadioRecorderLibVlcSharp.Program.Main(String[] args) in /media/RadioRecorderLibVlcSharp/Program.cs:line 19
Anyone can help me?
thanks
Can you try apt-get install vlc? That seems to help getting all the required plugins/deps on your system (though it will pull vlc 2.x from the official ubuntu rep probably).

How to launch another Android app using cocos2d-x?

I'm making a game with cocos2d-x for Android using C++. Now I'm looking for a way to open another Android App (likes YouTube, Google Play Store, ...) using their package name from inside my game through a button . I have searched around and found that it could be done in Java code with something like this:
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.package.address");
if (launchIntent != null) {
startActivity(launchIntent);//null pointer check in case package name was not found
}
My question is: Is it possible to open another Android App in my native code (.cpp files) or I have to put them in java side (.java files)? If I have to do it in .java files, where should I put it? I always work with .cpp files in Visual Studio, compile with cmd and run with emulator on Android Studio, I have never worked with .java files that generated by cocos2d-x in Android Studio, the engine just makes everything ready for me so I got a little confused here.
Update 1:
Abhishek Aryan's advice works but my Game crashed on resume when I'm in another App. I'm trying to performs some actions before opening others app and they might cause the crash because I could run it without any problem if I remove those action and leave openApp function alone.
My expect: Press the button => pause my game and open You Tube on Android => Press Back Button => pause You Tube and resume my game.
What happens: I could open You Tube but my App crashed when I press back button. I got the following error code from Android Studio:
A/libc: Fatal signal 11 (SIGSEGV) at 0x0004fb18 (code=1), thread 1975 (Thread-55)
Any idea how could I fix it?
My code :
auto imageOpeningAction = CallFunc::create([&]() {
mOpeningImage->setEnabled(true);
mOpeningImage->setOpacity(255);
mOpeningImage->setPosition(menuItem->getPosition());
mOpeningImage->runAction(fullScale);
});
auto imageClosingAction = CallFunc::create([&]() {
mOpeningImage->runAction(reverseScale);
mOpeningImage->setOpacity(0);
mOpeningImage->setEnabled(false);
});
auto openAnotherApp = CallFunc::create([&]() { // Open YouTube app
HelloWorld::openApp(packageName);
});
runAction(Sequence::create(imageOpeningAction->clone(), DelayTime::create(0.5f), openAnotherApp->clone(), nullptr));
Your attention and help is very much appreciated.
You need to use JNI for your requirement.
Create a method that open any app in your AppActivity.
public class AppActivity extends Cocos2dxActivity {
private static Activity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity=this;
}
public static void openOtherApp(String packageName){
Intent launchIntent = activity.getPackageManager().getLaunchIntentForPackage(packageName);
if (launchIntent != null) {
activity.startActivity(launchIntent);
}
}
}
Done !
Not yet, now only I need to call openOtherApp method from c++ so I create a method in my .cpp file.
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include "platform/android/jni/JniHelper.h"
#endif
void openApp(std::string packageName){
#if(CC_TARGET_PLATFORM==CC_PLATFORM_ANDROID)
JniMethodInfo methodInfo;
const char* class_name="org/cocos2dx/cpp/AppActivity";
const char* method_name="openOtherApp";
const char* parameter= "(Ljava/lang/String;)V";
if (! cocos2d::JniHelper::getStaticMethodInfo(methodInfo, class_name, method_name ,parameter )) {
return;
}
jstring jStringParam = methodInfo.env->NewStringUTF(packageName.c_str());
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID,jStringParam);
methodInfo.env->DeleteLocalRef(methodInfo.classID);
#endif
}
Want to open facebook call openApp(com.facebook.katana);

Pubnub library not compiling on Particle Photon

I am trying to publish a message using pubnub on the Particle Photon. The code snippet below comes straight out of the Pubnub example code.
The code will not compile, with the message from the compiler as follows:
PubNub/PubNub.h:87:47: error: expected class-name before '{' token
class PubSubClient: public PubNub_BASE_CLIENT {
^
PubNub/PubNub.h: In constructor 'PubSubClient::PubSubClient()':
PubNub/PubNub.h:23:28: error: class 'PubSubClient' does not have any field named 'WiFiClient'
#define PubNub_BASE_CLIENT WiFiClient
^
The code for this tiny project is as follows:
// This #include statement was automatically added by the Particle IDE.
#include "PubNub/PubNub.h"
char pubkey[] = "<key here>";
char subkey[] = "<key here>";
char channel[] = "Channel";
void setup() {
Serial.begin(9600);
Particle.publish("Serial set up");
PubNub.begin(pubkey, subkey);
}
void loop() {
TCPClient *client;
char msg[64] = "{\"photon\":\"on\"}";
client = PubNub.publish(channel, msg);
client->stop();
Delay (30000);
}
Has anyone had a similar problem, and if so, can you guide me as to how to fix this.
Thanks.
It looks like the library available in Build IDE was in an older version (0.0.1). Fixed, latest version (0.0.2) has been published.
To update library in your app you need to remove the PubNub library from your app in Apps drawer:
And then go to Libraries drawer, find PubNub library, click Include in App, select your app and confirm:

Playing wav/mp3 from Windows 7 service

I need to play a sound file (wav or mp3 is fine) from a service in Windows 7/2008... the way we did it in WinXP doesn't work anymore. I've followed this question Play wave file from a Windows Service (C#) with no success, in various combinations. The sound plays fine through the debugger but once I install it as a service it doesn't play, and event logs prove the call is being made. I've also followed the http://bresleveloper.blogspot.co.il/2012/06/c-service-play-sound-with-naudio.html link with the same result.
Code snippet follows below. It is a C# service with VS 2010, .Net 4.0, NAudio 1.5.4.0. I am using
InstallUtil to install/remove the service.
WRT the code, I comment out the Wav or MP3 stuff and one of the methods each time... they all play the sound sucessfully.
static class Program
{
[DllImport("kernel32.dll")]
public static extern Boolean AllocConsole();
static void Main(string[] args)
{
m_eventLog = new EventLog();
m_eventLog.Source = "EventLoggerSource";
if(args.Length > 0 && args[0].ToLower() == "/console")
{
AllocConsole();
EventLoggerApp app = new EventLoggerApp();
app.Start();
m_eventLog.WriteEntry("INFO (Calling Player)");
string fileFullPath=#"c:\aaasound\bunny_troubles.wav",fileFullPath2=#"c:\aaasound\dreams.mp3";
// Wav file
IWavePlayer wavePlayer=new WaveOutEvent(); // Method 1
IWavePlayer wavePlayer=new WasapiOut(NAudio.CoreAudioApi.AudioClientShareMode.Shared,false,100); // Method 2
AudioFileReader audioFile=new AudioFileReader(fileFullPath);
audioFile.Volume = (float)1.0;
wavePlayer.Init(audioFile);
// MP3 file
IWavePlayer wavePlayer=new WasapiOut(NAudio.CoreAudioApi.AudioClientShareMode.Shared,true,100); // Method 1- EventSync/not both work
IWavePlayer wavePlayer=new WasapiOut(NAudio.CoreAudioApi.AudioClientShareMode.Exclusive,false,100); // Method 2- EventSync must be false or throws an exception
WaveStream mp3Reader = new Mp3FileReader(fileFullPath2);
WaveChannel32 inputStream=new WaveChannel32(mp3Reader);
WaveStream wavStream=new WaveChannel32(inputStream);
wavePlayer.Init(wavStream);
//this.wavePlayer.PlaybackStopped += new EventHandler(wavePlayer_PlaybackStopped);
wavePlayer.Play();
while(wavePlayer.PlaybackState == PlaybackState.Playing)
{
Thread.Sleep(100);
}

Resources