python script instantiate GameObject on Unity photon network - python

I want to have a python (or something that can run in the Raspberry Pi console and also interact with MySQL) script running on my Raspberry Pi to instantiate a game object on my unity photon networked game, this is so people can send maps via a text file which my code can interperate and then the script will spawn all the gameObjects named in the file at the cords set and then the players are spawned in.
I know how to do all the other stuff on Raspberry Pi without an actual Unity game open on it to do that, I just need some way to make the python script spawn the gameobjects in before the players join. Thx - Billy.
The code is currently in C# which runs in an actual Unity game that can spawn stuff in, the code which does this looks like this:
StreamReader reader = new StreamReader(FileMapDIR);
string s = reader.ReadLine();
TerrainType = float.Parse(s);
if(TerrainType == 1){
GameObject myTerrainGO = (GameObject)PhotonNetwork.Instantiate("Terrain1", Terrain1Pos, Quaternion.identity, 0);
}
if(TerrainType == 2){
GameObject myTerrainGO = (GameObject)PhotonNetwork.Instantiate("Terrain2", Terrain1Pos, Quaternion.identity, 0);
}
if(TerrainType == 3){
GameObject myTerrainGO = (GameObject)PhotonNetwork.Instantiate("Terrain3", Terrain1Pos, Quaternion.identity, 0);
}
s = reader.ReadLine();
while(s != null){
char[] delimiter = {':'};
string[] feilds = s.Split(delimiter);
string objName = feilds[0];
float lx = float.Parse(feilds[1]);
float ly = float.Parse(feilds[2]);
float lz = float.Parse(feilds[3]);
float ra1 = float.Parse(feilds[4]);
Vector3 positionA = new Vector3(lx, ly, lz);
GameObject myCrateGO = (GameObject)PhotonNetwork.Instantiate(objName, positionA, Quaternion.Euler(0, ra1, 0), 0);
s = reader.ReadLine();
}
ingame = true;

Related

Serial communication between python + arduino and parsing string

I'm trying to send a set of [x, y] coordinates from python to arduino in order to control servo motors on a robot drivetrain. I'm taking the approach of sending a string in the format "x,y". On the arduino side, I'm trying to parse this string to get the x and y substrings. However the indexOf function doesn't return the proper index. Here is my code:
arduino = serial.Serial(port='COM3', baudrate=9600, timeout=.1)
def write_read(x):
arduino.write(bytes(x, 'utf-8'))
time.sleep(0.05)
data = arduino.readline()
return data
for coordinate in coordinates:
c = str(coordinate[0]) + ", " + str(coordinate[1])
print(write_read(c))
#include <Servo.h>
void setup() {
Serial.begin(9600);
Serial.setTimeout(1);
}
void loop() {
while (!Serial.available());
String coordinates = "" + Serial.readString();
// Serial.print(coordinates); //this prints normally as the string value
int i = coordinates.indexOf(',');
Serial.print(i);
}
When I send something like "-9.45, -16.3". The output is b'-1-1-1-1-10-1-1-1-1-1-1'. I'm not sure what's going on here or how to get the actual index (in this case it would be 5).

How to read the serial port with a arduino over python?

import serial
ser= serial.Serial('com5',9600)
while 1:
Value_from_arduino = ser.readline()
Zustand = float(Value_from_arduino)
print(Zustand)
if Zustand == 1:
ser.write(0)
print('off')
elif Zustand == 0:
ser.write(1)
print(on)
This was the Python code, now here the arduino code.
char serialData;
int pin=12;
int pin2 = 5;
int Value;
void setup(){
pinMode(pin,OUTPUT);
pinMode(pin2,INPUT);
Serial.begin(9600);
}
void loop(){
Value = digitalRead(pin2);
Serial.println(Value);
delay(250);
while(Serial.available()){
serialData = Serial.read();
Serial.print(serialData);
if(serialData = '1'){
digitalWrite(pin,HIGH);
}
else if(serialData = '0'){
digitalWrite(pin,LOW);
}
}
}
My problem is, when i run my python code, it stops when he gets the Value 0 from my arduino.
Here is the report from python:
Zustand = float(Value_from_Arduino)
ValueError: could not convert string to float: b'\x000\r\n'
Python immediatly stops, but he puts the LED on.
The LED should be on if Python gets the value of 0, he do but then he just end run.
The LED should go on if value is 0 and of if value is 1.
You need to decode the serial bytes from the serial port.
Replace the Zustand = line in your code
Value_from_arduino = ser.readline()
Zustand = float(ser_bytes[0:len(Value_from_arduino )-2].decode("utf-8"))
Please check here https://makersportal.com/blog/2018/2/25/python-datalogger-reading-the-serial-output-from-arduino-to-analyze-data-using-pyserial
also try, if encodings doesn't work well
import struct
Zustand, = struct.unpack('<f',Value_from_arduino )
Finally i have found out please replace these lines of code
Steps -> Read,Decode to string, Strip /n and /r, Convert to float
please check here https://problemsolvingwithpython.com/11-Python-and-External-Hardware/11.04-Reading-a-Sensor-with-Python/
Value_from_arduino = ser.readline()
Value_from_arduino = Value_from_arduino.decode()
Value_from_arduino = Value_from_arduino.rstrip()
Zustand = float(Value_from_arduino)
Hope this Works..

Windows pipes: Write from C - read in Python

I'd like to transmit a few bytes of data though a pipe to plot it from python.
I started with some snippets I found here but I cant get them working.
I've created the pipe like this:
int main(void){
HANDLE hPipe;
char buffer[24];
DWORD dwRead;
hPipe = CreateNamedPipe(TEXT("\\\\.\\pipe\\Pipe"),
PIPE_ACCESS_DUPLEX | PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, // FILE_FLAG_FIRST_PIPE_INSTANCE is not needed but forces CreateNamedPipe(..) to fail if the pipe already exists...
PIPE_WAIT,
1,
24 * 16,
24 * 16,
NMPWAIT_USE_DEFAULT_WAIT,
NULL);
while (hPipe != INVALID_HANDLE_VALUE)
{
if (ConnectNamedPipe(hPipe, NULL) != FALSE) // wait for someone to connect to the pipe
{
while (ReadFile(hPipe, buffer, sizeof(buffer) - 1, &dwRead, NULL) != FALSE)
{
/* add terminating zero */
buffer[dwRead] = '\0';
/* do something with data in buffer */
printf("%s", buffer);
}
}
DisconnectNamedPipe(hPipe);
}
return 0;}
If I execute the following code it writes but the read part blocks:
import time
import struct
f = open(r'\\.\\pipe\\Pipe', 'r+b', 0)
i = 1
sss='ccccc'
while True:
s = sss.format(i)
i += 1
f.write(struct.pack('I', len(s)) + s) # Write str length and str
f.seek(0) # EDIT: This is also necessary
print 'Wrote:', s
n = struct.unpack('I', f.read(4))[0] # Read str length
s = f.read(n) # Read str
f.seek(0) # Important!!!
print 'Read:', s
time.sleep(2)
I tried commenting the ReadFile part in the C code but It did not work. Is there any other way to achieve this? I want to write from C and read from python. I tried writing into the pipe with CreateFile (from C) and it worked as expected. I only need the read part with python.
On most systems pipe is one-directional and you use two pipes to get two-directional (bidirectional) connection.
In your Python code you can open two connections
and then you don't need seek
import time
import struct
wf = open(r'Pipe', 'wb', 0)
rf = open(r'Pipe', 'rb', 0)
i = 0
template = 'Hello World {}'
while True:
i += 1
text = template.format(i)
# write text length and text
wf.write(struct.pack('I', len(text)))
wf.write(text)
print 'Wrote:', text
# read text length and text
n = struct.unpack('I', rf.read(4))[0]
read = rf.read(n)
print 'Read:', read
time.sleep(2)
EDIT: tested on Linux Mint 17, Python 3.4 & 2.7
I've solved it with PyWin32(http://sourceforge.net/projects/pywin32/files/) which seems to be the right tool for windows. I would rather use something more cross-plataform oriented but it has solved the problem.

Can Python read from a Windows Powershell namedpipe?

I have the following named pipe created in Windows Powershell.
# .NET 3.5 is required to use the System.IO.Pipes namespace
[reflection.Assembly]::LoadWithPartialName("system.core") | Out-Null
$pipeName = "pipename"
$pipeDir = [System.IO.Pipes.PipeDirection]::InOut
$pipe = New-Object system.IO.Pipes.NamedPipeServerStream( $pipeName, $pipeDir )
Now, what i need is some Python code snippet to read from the above named pipe created. Can Python do that ?
Thanks in advance !
Courtesy :http://jonathonreinhart.blogspot.com/2012/12/named-pipes-between-c-and-python.html
Here's the C# Code
using System;
using System.IO;
using System.IO.Pipes;
using System.Text;
class PipeServer
{
static void Main()
{
var server = new NamedPipeServerStream("NPtest");
Console.WriteLine("Waiting for connection...");
server.WaitForConnection();
Console.WriteLine("Connected.");
var br = new BinaryReader(server);
var bw = new BinaryWriter(server);
while (true)
{
try
{
var len = (int)br.ReadUInt32(); // Read string length
var str = new string(br.ReadChars(len)); // Read string
Console.WriteLine("Read: \"{0}\"", str);
//str = new string(str.Reverse().ToArray()); // Aravind's edit: since Reverse() is not working, might require some import. Felt it as irrelevant
var buf = Encoding.ASCII.GetBytes(str); // Get ASCII byte array
bw.Write((uint)buf.Length); // Write string length
bw.Write(buf); // Write string
Console.WriteLine("Wrote: \"{0}\"", str);
}
catch (EndOfStreamException)
{
break; // When client disconnects
}
}
}
}
And here's the Python code:
import time
import struct
f = open(r'\\.\pipe\NPtest', 'r+b', 0)
i = 1
while True:
s = 'Message[{0}]'.format(i)
i += 1
f.write(struct.pack('I', len(s)) + s) # Write str length and str
f.seek(0) # EDIT: This is also necessary
print 'Wrote:', s
n = struct.unpack('I', f.read(4))[0] # Read str length
s = f.read(n) # Read str
f.seek(0) # Important!!!
print 'Read:', s
time.sleep(2)
Convert the C# code into a .ps1 file.

Check to see if system volume is muted?

I am working on a project that plays audio for part of the program. I would like to be able to display a message if the user's system volume is muted. I am using Python on Windows.
Use the Windows Mixer API. I've found this article for you, and attached the relevant code:
(From MS KB 181550: "Monitor Audio Volume Levels")
This is in C, but it can be "translated" to Python as well.
I hope that helps.
#include <windows.h>
#include <mmsystem.h>
MMRESULT rc; // Return code.
HMIXER hMixer; // Mixer handle used in mixer API calls.
MIXERCONTROL mxc; // Holds the mixer control data.
MIXERLINE mxl; // Holds the mixer line data.
MIXERLINECONTROLS mxlc; // Obtains the mixer control.
// Open the mixer. This opens the mixer with a deviceID of 0. If you
// have a single sound card/mixer, then this will open it. If you have
// multiple sound cards/mixers, the deviceIDs will be 0, 1, 2, and
// so on.
rc = mixerOpen(&hMixer, 0,0,0,0);
if (MMSYSERR_NOERROR != rc) {
// Couldn't open the mixer.
}
// Initialize MIXERLINE structure.
ZeroMemory(&mxl,sizeof(mxl));
mxl.cbStruct = sizeof(mxl);
// Specify the line you want to get. You are getting the input line
// here. If you want to get the output line, you need to use
// MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT.
mxl.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_WAVEIN;
rc = mixerGetLineInfo((HMIXEROBJ)hMixer, &mxl,
MIXER_GETLINEINFOF_COMPONENTTYPE);
if (MMSYSERR_NOERROR == rc) {
// Couldn't get the mixer line.
}
// Get the control.
ZeroMemory(&mxlc, sizeof(mxlc));
mxlc.cbStruct = sizeof(mxlc);
mxlc.dwLineID = mxl.dwLineID;
mxlc.dwControlType = MIXERCONTROL_CONTROLTYPE_PEAKMETER;
mxlc.cControls = 1;
mxlc.cbmxctrl = sizeof(mxc);
mxlc.pamxctrl = &mxc;
ZeroMemory(&mxc, sizeof(mxc));
mxc.cbStruct = sizeof(mxc);
rc = mixerGetLineControls((HMIXEROBJ)hMixer,&mxlc,
MIXER_GETLINECONTROLSF_ONEBYTYPE);
if (MMSYSERR_NOERROR != rc) {
// Couldn't get the control.
}
// After successfully getting the peakmeter control, the volume range
// will be specified by mxc.Bounds.lMinimum to mxc.Bounds.lMaximum.
MIXERCONTROLDETAILS mxcd; // Gets the control values.
MIXERCONTROLDETAILS_SIGNED volStruct; // Gets the control values.
long volume; // Holds the final volume value.
// Initialize the MIXERCONTROLDETAILS structure
ZeroMemory(&mxcd, sizeof(mxcd));
mxcd.cbStruct = sizeof(mxcd);
mxcd.cbDetails = sizeof(volStruct);
mxcd.dwControlID = mxc.dwControlID;
mxcd.paDetails = &volStruct;
mxcd.cChannels = 1;
// Get the current value of the peakmeter control. Typically, you
// would set a timer in your program to query the volume every 10th
// of a second or so.
rc = mixerGetControlDetails((HMIXEROBJ)hMixer, &mxcd,
MIXER_GETCONTROLDETAILSF_VALUE);
if (MMSYSERR_NOERROR == rc) {
// Couldn't get the current volume.
}
volume = volStruct.lValue;
// Get the absolute value of the volume.
if (volume < 0)
volume = -volume;

Categories

Resources