Is this the right way to "publish" msg to the topic? - python

Currently learning ROS with LGSVL Simulator. I want to publish to "/move_base_simple/goal" topic.
In main code just showing important "import" and the end of the code
import rospy
import roslibpy
from rospy import rostime
import lgsvl
import logging
from environs import Env
from geometry_msgs.msg import PoseStamped
import publisher
### LGSVL SETUP ###
...
###################
ego.set_destination(publisher.GoalPublisher.publish_2d_nav_goal(self=publisher.GoalPublisher,pose_x=9425.16015625, pose_y=9823.15527344, pose_z=0.0))
ros = roslibpy.Ros(host='localhost', port=9090)
ros.run()
sim.run()
This is my publisher
import rospy
import rospkg
import std_msgs
from geometry_msgs.msg import PoseStamped
class GoalPublisher():
def __init__(self):
rospy.init_node('webapp', disable_signals=True)
self.goal_publisher = rospy.Publisher("move_base_simple/goal", PoseStamped, queue_size=10)
def publish_2d_nav_goal(self, pose_x, pose_y, pose_z):
goal = PoseStamped()
goal.header.stamp = rospy.Time.now()
goal.header.frame_id = "map"
goal.pose.position.x = pose_x
goal.pose.position.y = pose_y
goal.pose.position.z = pose_z
goal.pose.orientation.x = 0.0
goal.pose.orientation.y = 0.0
goal.pose.orientation.z = -0.663932738254
goal.pose.orientation.w = 0.747792296747
self.goal_publisher.publish(goal)
When i am trying to start my main code, i get this error:rospy.exceptions.ROSInitException: time is not initialized. Have you called init_node()?
Do i need to add "rospy.init_node(...)" in the main code ? Or how can i fix this issue ?

You need to call rospy.init_node() for every ros node you create. You can call it wherever you want in the node, however, it must be called before trying to use anything in the ros api. In this example your publisher is fine but you're calling roslibpy.Ros() before initializing the main code as it's own node.
rospy.init_node('main_node')
ego.set_destination(publisher.GoalPublisher.publish_2d_nav_goal(self=publisher.GoalPublisher,pose_x=9425.16015625, pose_y=9823.15527344, pose_z=0.0))
ros = roslibpy.Ros(host='localhost', port=9090)
ros.run()
sim.run()

Related

Importing a deck in anki python

I am working on an addon, for anki, which requires me to import a new deck using its python API. I found the function called test_apkg which seems to have parts which do that. I tried implimenting that below, I am getting no errors, however the deck does not get imported. How do I make my testFunction() import a deck for anki?
from aqt import mw
from aqt.utils import showInfo, qconnect
from aqt.qt import *
from anki.importing import *
import os
from anki.collection import Collection as aopen
#from anki.pylib.tests.shared import getEmptyCol
from .shared import getEmptyCol
def testFunction() -> None:
file = "flashcards.apkg"
col = getEmptyCol()
apkg = r"path_to_file/flashcards.apkg"
imp = AnkiPackageImporter(col, apkg)
imp.run()
# create a new menu item, "test"
action = QAction("Import", mw)
# set it to call testFunction when it's clicked
qconnect(action.triggered, testFunction)
# and add it to the tools menu
mw.form.menuTools.addAction(action)

Adafruit Doesn't work with Multiprocessing

These error can be reproduce with any adafruit device.These example is for GPS.
I have tested several adafruit products, they are all great quality. However they all seems to present the same problem when use with the multiprocessing module. The script dose not run and throws a Segmentation fault (core dumped). The script runs with threading but not multiprocessing.
These does not works:
import time
import board
import adafruit_bno055
import threading
import multiprocessing
fpsFilt = 0
timeStamp = 0
i2c = board.I2C()
sensor = adafruit_bno055.BNO055_I2C(i2c)
def test():
while True:
print("Quaternion: {}".format(sensor.quaternion))
Gps = multiprocessing.Process(target=test)
Gps.start()
But these works:
import time
import board
import adafruit_bno055
import threading
import multiprocessing
fpsFilt = 0
timeStamp = 0
i2c = board.I2C()
sensor = adafruit_bno055.BNO055_I2C(i2c)
def test():
while True:
print("Quaternion: {}".format(sensor.quaternion))
Gps = threading.Thread(target=test)
Gps.start()
Is there any way to use an adafruit product with multiprocessing?Thanks.
Try this program. I have eliminated all the global variables, initialized the device entirely in the secondary Process, and protected the program's entry point with a test for __main__. These are all standard practices when writing this type of program.
Otherwise it is the same code as your program.
import time
import board
import adafruit_bno055
import threading
import multiprocessing
def test():
i2c = board.I2C()
sensor = adafruit_bno055.BNO055_I2C(i2c)
while True:
print("Quaternion: {}".format(sensor.quaternion))
def main():
Gps = multiprocessing.Process(target=test)
Gps.start()
if __name__ == "__main__":
main()
while True:
time.sleep(1.0)

Python Class Initialization Error. Cannot initialize an Imported class

I am trying to initialize a class ModuleLMPC from commander.py which is the main class. I get following error.
File "D:\CARLA\PythonAPI\examples\fnc\commander.py", line 89, in __init__
self.LMPC = ModuleLMPC(self.dt, self.LapTime, self.maxLaps, self.Map)
TypeError: 'module' object is not callable
I import ModuleLMPC as:
from ModuleLMPC import ModuleLMPC
I am trying to import ModuleLMPC from ModuleLMPC.py file. They have the same name.
The ModuleLMPC first few lines look like:
from SysModel import Simulator, PID
from Classes import ClosedLoopData, LMPCprediction
from PathFollowingLTVMPC import PathFollowingLTV_MPC
from PathFollowingLTIMPC import PathFollowingLTI_MPC
from LMPC import ControllerLMPC
from Utilities import Regression
import numpy as np
import pdb
import pickle
class ModuleLMPC(object):
def __init(self, dt, Time, maxlaps, map):
# ======================================================================================================================
# ============================ Choose which controller to run ==========================================================
# ======================================================================================================================
self.RunPID = 1
self.RunMPC = 1
And I initialize ModuleLMPC in commander.py as:
self.LMPC = ModuleLMPC(self.dt, self.LapTime, self.maxLaps, self.Map)
I even moved everything in the same folder. Not sure what the error means.

How to trigger a function without importing everything?

I programmed a gateway to a opcua-server with python-opcua.
The gateway is subscribing some values in the opcua. That is working good and fast.
Now I want to call a script that writes to the opcua.
In principle, it works too. But because I have to import the whole gateway(and all opcua stuff), it is very slow...
My Question: Is is possible to trigger a function in my class-instance without imorting everything?
To start e.g. function setBool(), I have to import Gateway...
#!/usr/bin/env python3.5 -u
# -*- coding: utf-8 -*-
import time
import sys
import logging
from logging.handlers import RotatingFileHandler
from threading import Thread
from opcua import Client
from opcua import ua
from subscribeOpcua import SubscribeOpcua
from cmdHandling import CmdHandling
from keepConnected import KeepConnected
class Gateway(object):
def __init__(self):
OPCUA_IP = '1.25.222.222'
OPCUA_PORT = '4840'
OPCUA_URL = "opc.tcp://{}:{}".format(OPCUA_IP, str(OPCUA_PORT))
addr = "OPCUA-URL:{}.".format(OPCUA_URL)
# Setting up opcua-handler
self.client = Client(OPCUA_URL)
self.opcuaHandlers = [SubscribeOpcua()]
# Connect to opcua
self.connecter = KeepConnected(self.client,self.opcuaHandlers)
self.connecter.start()
def setBool(self, client):
"""Set e boolean variable on opcua-server.
"""
path = ["0:Objects","2:DeviceSet"...]
root = client.get_root_node()
cmd2opcua = root.get_child(path)
cmd2opcua.set_value(True)
if __name__ == "__main__":
"""Open connecter when gateway is opened directly.
"""
connect = Gateway()
The only way to prevent a code from runing when importing a module is to put it inside a method:
def import_first_part():
global re
global defaultdict
print('import this first part')
# import happen locally
# because when you do `import re` actually
# re = __import__('re')
import re
from collections import defaultdict
def import_second_part():
print('import pandas')
# really unnecessary check here because if we import
# pandas for the second time it will just retrieve the object of module
# the code of module is executed only in the first import in life of application.
if 'pandas' in globals():
return
global pandas
import pandas
def use_regex():
import_first_part()
# do something here
if __name__ == '__main__':
use_regex()
re.search('x', 'xb') # works fine
I checked that 'pandas' is in global scope before reimport it again but really this is not necessary, because when you import a module for the second time it's just retrieved no heavy calculation again.

Update variable from imported module with Python when using Threading

In a project, I would like to separate the visualization and calculation in two different modules. The goal is to transfer the variables of the calculation-module to a main-script, in order to visualize it with the visualization-script.
Following this post
Using global variables between files?,
I am able to use a config-script in order to transfer a variable between to scripts now. But unfortunately, this is not working when using threading. The Output of the main.py is always "get: 1".
Does anyone have an idea?
main.py:
from threading import Thread
from time import sleep
import viz
import change
add_Thread = Thread(target=change.add)
add_Thread.start()
viz.py:
import config
from time import sleep
while True:
config.init()
print("get:", config.x)
sleep(1)
config.py:
x = 1
def init():
global x
change.py:
import config
def add():
while True:
config.x += 1
config.init()
OK, fount the answer by myself. Problem was in the "main.py". One has to put the "import viz" after starting the thread:
from threading import Thread
from time import sleep
import change
add_Thread = Thread(target=change.add)
add_Thread.start()
import viz

Categories

Resources