Unity3D IP Camera - unity3d

I'm using a Marmitek IP RoboCam 641 to import a video feed into unity. I use constantly refreshing snapshots to update a GUI.DrawTexture on the screen. However I recently switched to the Marmitek from a Velleman wireless ip colour camera. Now my snapshot only refreshes once or twice, before stopping and giving this error:
UnityException: Recv failure: Connection was reset
SEMTEX+c__Iterator0.MoveNext () (at Assets/Scripts/SEMTEX.cs:37)
And this is my code:
using UnityEngine;
using System.Collections;
public class SEMTEX : MonoBehaviour {
//public string uri = "http://192.168.1.101/snapshot.cgi";//velleman
public string uri = "http://192.168.1.30/cgi/jpg/image.cgi";//marmitek
public string username = "admin";
public string password = "admin";
int calc = 0;
Texture2D cam;
Texture2D cam2;
public void Start() {
cam=new Texture2D(1, 1, TextureFormat.RGB24, true);
StartCoroutine(Fetch());
cam2=new Texture2D(1, 1, TextureFormat.RGB24, true);
StartCoroutine(Fetch());
}
public IEnumerator Fetch() {
while(true) {
Debug.Log("fetching... "+Time.realtimeSinceStartup);
WWWForm form = new WWWForm();
form.AddField("dummy", "field"); // required by WWWForm
WWW www = new WWW(uri, form.data, new System.Collections.Generic.Dictionary<string,string>() { // using www.headers is depreciated by some odd reason
{"Authorization", "Basic " + System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(username+":"+password))}
});
yield return www;
if(!string.IsNullOrEmpty(www.error))
throw new UnityException(www.error);
www.LoadImageIntoTexture(cam);
www.LoadImageIntoTexture(cam2);
}
}
public void OnGUI() {
GUI.DrawTexture(new Rect(0,0,Screen.width/2,Screen.height), cam);
calc = (Screen.width/2-100);
GUI.DrawTexture(new Rect(calc,0,Screen.width/2,Screen.height), cam2);
Debug.Log (Screen.width);
}
Does anyone have any ideas regarding my error?

Related

How would I get a Texture in the project and send it over to discord using a webhook? Unity

What I am trying to do is take a texture(any texture) from unity and use a webhook from discord to send it to discord.
This is what I have so far keep in mind I started coding not long ago so I'm not very familiar with this;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class SendMessage : MonoBehaviour
{
public string Message, Subject;
public string webhook;
public Texture2D screenshot;
// Start is called before the first frame update
void Start()
{
}
IEnumerator SendWebHook(string link, string message, System.Action<bool> action)
{
WWWForm form = new WWWForm();
form.AddField("content", message + screenshot.EncodeToPNG());
using (UnityWebRequest www = UnityWebRequest.Post(link, form))
{
yield return www.SendWebRequest();
if(www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
action(false);
}
else
{
action(true);
}
}
}
public void send()
{
StartCoroutine(SendWebHook(webhook, Subject + Message, (success) =>
{
if(success)
{
Debug.Log("good");
}
}));
}
}

Why does Post request to OpenAI in Unity result in error 400?

I am trying to use GPT3 in a game I am making but I can't seem to be able to call the OpenAI API correctly. I got most of this from the Unity docs.
Here is the code I am using:
public class gpt3_complete : MonoBehaviour
{
public string model;
public string prompt;
public int len;
public string temp;
public string api_key = "<key>";
void Start()
{
StartCoroutine(Upload());
}
IEnumerator Upload()
{
WWWForm form = new WWWForm();
form.AddField("model", model);
form.AddField("prompt", prompt);
form.AddField("max_tokens", len);
form.AddField("temperature", temp);
//form.headers.Add("Authorization", "Bearer "+api_key);
using (UnityWebRequest www = UnityWebRequest.Post("https://api.openai.com/v1/completions", form))
{
www.SetRequestHeader("Authorization", "Bearer " + api_key);
www.SetRequestHeader("Content-Type", "application/json");
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log(www.error);
}
else
{
Debug.Log(www.result);
Debug.Log("Form upload complete!");
}
}
}
}
This always returns: 400 Bad Request.
The GPT3 docs can be found here: https://beta.openai.com/docs/api-reference/completions/create
Any idea why this is?
This is my first time making any web requests in unity so I'm probably missing something obvious.
Thanks!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.Text;
public class OpenAIRequest : MonoBehaviour
{
public string apiKey = "YOUR_API_KEY_HERE";
public string prompt = "Once upon a time, in a land far far away, there lived a brave knight";
public string model = "text-davinci-002";
public int maxTokens = 100;
void Start()
{
StartCoroutine(GetOpenAIResponse());
}
IEnumerator GetOpenAIResponse()
{
string url = "https://api.openai.com/v1/engines/" + model + "/completions";
string requestData = "{\"prompt\": \"" + prompt + "\", \"max_tokens\": " + maxTokens + "}";
UnityWebRequest request = new UnityWebRequest(url, "POST");
byte[] bodyRaw = Encoding.UTF8.GetBytes(requestData);
request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
request.SetRequestHeader("Authorization", "Bearer " + apiKey);
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
Debug.Log(request.error);
}
else
{
string response = request.downloadHandler.text;
Debug.Log(response);
}
}
}
result

photon pun2 unity playfab email and password auth

i want to make email auth with playfab and photon istead of custom id auth shown in photon quickstart guide playfab. i tried this script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Realtime;
using Photon.Pun;
using PlayFab;
using PlayFab.ClientModels;
using TMPro;
public class pfauth : MonoBehaviour
{
#region objects
[Header (" register ")]
public TMP_InputField user;
public TMP_InputField email;
public TMP_InputField pass;
public GameObject regpanel;
[Header(" login ")]
public TMP_InputField luser;
public TMP_InputField lpass;
public GameObject loginpanel;
[Header(" Other gameobjects ")]
public TMP_Text message;
public bool IsAuthenticated = false;
public GameObject prpo;
public float sec;
private string _playFabPlayerIdCache;
LoginWithPlayFabRequest loginrequest;
#endregion
public void Start() //set the loginpanel as disable at start
{
loginpanel.SetActive(false);
regpanel.SetActive(true);
}
public void login()
{
loginrequest = new LoginWithPlayFabRequest();
loginrequest.Username = luser.text;
loginrequest.Password = lpass.text;
PlayFabClientAPI.LoginWithPlayFab(loginrequest, \\in this line how can i call requestphotontoken result => {
//if account found
message.text = "welcome back" + user.text + "loging in...";
StartCoroutine("waitforempty"); //hide the text after few seconds
IsAuthenticated = true;
Debug.Log("logged in");
}, error => {
message.text = "Sorry! Failed to login(" + error.ErrorMessage + ")";
StartCoroutine("waitforempty"); //hide the text after few seconds
Debug.Log(error.ErrorDetails);
IsAuthenticated = false;
}, null);
}
public void register()
{
RegisterPlayFabUserRequest request = new RegisterPlayFabUserRequest();
request.Email = email.text;
request.Password = pass.text;
request.Username = user.text;
PlayFabClientAPI.RegisterPlayFabUser(request, \\in this line how can i call requestphotontoken result =>
{
message.text = "Your account has been created!";
StartCoroutine("waitforempty"); //hide the text after few seconds
prpo.SetActive(true);
}, error =>
{
message.text = "Sorry! Failed to create your account(" + error.ErrorMessage + ")";
StartCoroutine("waitforempty"); //hide the text after few seconds
});
}
public void regpan()
{
loginpanel.SetActive(false);
regpanel.SetActive(true);
}
public void logbak()
{
loginpanel.SetActive(true);
regpanel.SetActive(false);
}
IEnumerator waitforempty() //hide the text after few seconds
{
yield return new WaitForSeconds(sec);
message.text = " ";
}
private void RequestPhotonToken(LoginResult obj)
{
LogMessage("PlayFab authenticated. Requesting photon token...");
//We can player PlayFabId. This will come in handy during next step
_playFabPlayerIdCache = obj.PlayFabId;
PlayFabClientAPI.GetPhotonAuthenticationToken(new GetPhotonAuthenticationTokenRequest()
{
PhotonApplicationId = PhotonNetwork.PhotonServerSettings.AppSettings.AppIdRealtime
}, AuthenticateWithPhoton, OnPlayFabError);
}
/*
* Step 3
* This is the final and the simplest step. We create new AuthenticationValues instance.
* This class describes how to authenticate a players inside Photon environment.
*/
private void AuthenticateWithPhoton(GetPhotonAuthenticationTokenResult obj)
{
LogMessage("Photon token acquired: " + obj.PhotonCustomAuthenticationToken + " Authentication complete.");
//We set AuthType to custom, meaning we bring our own, PlayFab authentication procedure.
var customAuth = new AuthenticationValues { AuthType = CustomAuthenticationType.Custom };
//We add "username" parameter. Do not let it confuse you: PlayFab is expecting this parameter to contain player PlayFab ID (!) and not username.
customAuth.AddAuthParameter("username", _playFabPlayerIdCache); // expected by PlayFab custom auth service
//We add "token" parameter. PlayFab expects it to contain Photon Authentication Token issues to your during previous step.
customAuth.AddAuthParameter("token", "");
//We finally tell Photon to use this authentication parameters throughout the entire application.
PhotonNetwork.AuthValues = customAuth;
Debug.Log(PhotonNetwork.ConnectUsingSettings().ToString());
}
private void OnPlayFabError(PlayFabError obj)
{
LogMessage(obj.GenerateErrorReport());
}
public void LogMessage(string message)
{
Debug.Log("PlayFab + Photon Example: " + message);
}
}
but in the "PlayFabClientAPI.LoginWithPlayFab(loginrequest, \in this line how can i call requestphotontoken" result line in both login and register void when i try to call RequestPhotonToken i shows this error-
Cannot convert methord group to function
please help
Photon PUN 2
Playfab latest

Unity Mirror - networked game object not showing up

I'm using Unity Mirror for networking my app so that a central server (not host) can send commands to the clients it is connected to.
On play, the "game" will make the program a client or server automatically on play, so i don't have to use the Client/Server only buttons provided by the NetworkManagerHUD.
Currently I'm facing 2 problems:
Client disconnects right after a connection with server is made. When I override the OnClientConnect function, I put the line base.OnClientConnect(conn). After stepping into the original function, I conclude it is the autoCreatePlayer set to true that is causing this problem. (the server and client are two instances of the program running on the same computer as I can only test using localhost).
public override void OnClientConnect(NetworkConnection conn)
{
base.OnClientConnect(conn); //This line causes the error message
clientConnected = true;
GameObject[] prefabs = Resources.LoadAll<GameObject>("NetworkingComponents");
foreach (var prefab in prefabs)
{
NetworkClient.RegisterPrefab(prefab);
}
GameObject[] gos = Resources.LoadAll<GameObject>("NetworkingComponents");
}
Perhaps the most critical issue. Referring to the previous problem, if i did remove the line
base.OnClientConnect(conn), client can connect, but all networked gameobjects (with NetworkIdentity) are still not showing up when connected as client, even though the NetworkManagerHUD says the program is connected as client. (Strangely, they are showing up if connected as Server.)
Here is the rest of the overriden NetworkManager code.
public class MyNetworkManager : NetworkManager
{
public GameObject dropdown;
public Canvas canvas;
//---------------------------Networking stuff----------------------------------
public List<NetworkNode> networkedNodes { get; } = new List<NetworkNode>();
public List<Settings> networkedSettings { get; } = new List<Settings>();
public List<NetworkedVisualisersDisplay> visualisersDisplays { get; } = new List<NetworkedVisualisersDisplay>();
public List<Visualiser> visualisers{ get; } = new List<Visualiser>();
public static MyNetworkManager instance = null;
public NetworkedVisualisersDisplay visDisplayPrefab;
public NetworkNode networkNode;
private string homeName;
public volatile bool clientConnected = false;
public bool IsClientConnected()
{
return clientConnected;
}
//the purpose of having a delay is that we need to determine if the call to StartClient() actually started the player as a client. It could fail if it’s the first player instance on the network.
public IEnumerator DelayedStart()
{
//base.Start();
StartClient();
yield return new WaitForSeconds(2);
print("conn count " + NetworkServer.connections.Count);
if (!IsClientConnected())
{
NetworkClient.Disconnect();
print(“starting as server”);
StartServer();
clientConnected = false;
}
else
{
print("starting as client");
}
visDisplayPrefab = Resources.Load<NetworkedVisualisersDisplay>("NetworkingComponents/NetworkedVisualisersDisplay");
if (instance == null)
{
instance = this;
print("instance = " + this);
}
else
{
print("manager destroyed");
Destroy(gameObject);
}
yield return null;
}
//-----------------------------------------------------------------------------
public override void Start(){
StartCoroutine(DelayedStart());
}
public override void OnStartServer()
{
GameObject[] prefabs = Resources.LoadAll<GameObject>("NetworkingComponents");
foreach (var prefab in prefabs)
{
spawnPrefabs.Add(prefab);
}
}
public override void OnServerChangeScene(string scenename)
{
if (scenename.Equals("Visualisers"))
{
for (int i = 0; i < visualisersDisplays.Count; i++)
{
var conn = networkedNodes[i].connectionToClient;
NetworkedVisualisersDisplay visSceneInstance = Instantiate(visualisersDisplays[i]);
NetworkServer.Destroy(conn.identity.gameObject);
NetworkServer.ReplacePlayerForConnection(conn, visSceneInstance.gameObject);
}
}
else if (Settings.Instance.sceneNames.Contains(scenename))
{
for (int i = 0; i < visualisersDisplays.Count; i++)
{
var conn = visualisers[i].connectionToClient;
var visInstance = Instantiate(visualisers[i]);
NetworkServer.Destroy(conn.identity.gameObject);
NetworkServer.ReplacePlayerForConnection(conn, visInstance.gameObject);
}
}
}
public override void OnServerAddPlayer(NetworkConnection conn)
{
NetworkNode n = Instantiate(networkNode);
NetworkServer.AddPlayerForConnection(conn, n.gameObject);
NetworkNode.instance.DisplayMessage();
}
public override void OnClientConnect(NetworkConnection conn)
{
base.OnClientConnect(conn);
//we are connected as a client
clientConnected = true;
GameObject[] prefabs = Resources.LoadAll<GameObject>("NetworkingComponents");
foreach (var prefab in prefabs)
{
NetworkClient.RegisterPrefab(prefab);
}
}
}
Any help will be greatly appreciated!

Unity3D WWW Post data async

I want to post a JSON to a website using the WWW class, But I get this answer from the server: "Synchronization problem.". Is there a way to change from sync to async? Thank You
You can run your WWW job in a coroutine (WWW supports this well):
using UnityEngine;
public class PostJSON : MonoBehaviour {
void Start () {
string url = "http://your_url_endpoint";
WWWForm form = new WWWForm();
Hashtable headers = form.headers;
headers["Content-Type"] = "application/json";
Hashtable data = new Hashtable();
data["message"] = "a sample message sent to service as json";
string json = JSON.JsonEncode(data);
byte[] bytes = Encoding.UTF8.GetBytes(json);
WWW www = new WWW(url, bytes, headers);
StartCoroutine(WaitForRequest(www));
}
IEnumerator WaitForRequest(WWW www)
{
yield return www
// check for errors
if (www.error == null)
{
Debug.Log("WWW Ok!: " + www.data);
} else {
Debug.Log("WWW Error: "+ www.error);
}
}
}
Here you have a running project which I use to talk to a json based REST service called KiiCloud:
http://blog.kii.com/?p=2939
HTH
The answer from German was very helpful, but I made some tweaks so that it'll compile and run (with sample serialization / deserialization bits).
Just pass in the BaseUrl you want to post to, i.e.
http://www.domain.com/somecontroller/someaction or whatever.
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class Person
{
public string Name;
}
[Serializable]
public class Response
{
public string SomeValue;
}
public class PostJSON : MonoBehaviour
{
public string BaseUrl;
private WWWForm form;
private Dictionary<string, string> headers = null;
void Start ()
{
var basUrlNotSpecified = string.IsNullOrEmpty(BaseUrl);
if(basUrlNotSpecified)
{
Debug.LogWarning("BaseUrl value not specified. Post abandoned.");
return;
}
form = new WWWForm();
headers = form.headers;
headers["Content-Type"] = "application/json";
headers["Accept"] = "application/json";
var person = new Person
{
Name = "Iulian Palade"
};
var json = JsonUtility.ToJson(person);
byte[] bytes = Encoding.UTF8.GetBytes(json);
WWW www = new WWW(BaseUrl, bytes, headers);
StartCoroutine(WaitForRequest(www));
}
IEnumerator WaitForRequest(WWW www)
{
yield return www;
if (www.error == null)
{
Debug.Log("WWW Ok!: " + www.text);
var response = JsonUtility.FromJson<Response>(www.text);
Debug.Log(response.SomeValue);
}
else
{
Debug.Log("WWW Error: "+ www.error);
}
}
}