Where do I put in the CHPROPS?
Should I put it in sitepackages and import it in the beginning of the code?
Keep getting “CHPROPS” is not defined no matter where in the code I put it in.
Thx again for the help!
Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
Where do I put in the CHPROPS?
Should I put it in sitepackages and import it in the beginning of the code?
Keep getting “CHPROPS” is not defined no matter where in the code I put it in.
Thx again for the help!
Ok thx for your help I get the full readout now
Listing all services and characteristics
Now I want to get the raw values of all the sensors and print them.
You talked about setting up a semafore system?
I am totally new to this can you explain more in-depth please?
The code till now:
import cb
import time
class HexiwearManager (object):
def __init__(self):
self.peripheral = None
def did_discover_peripheral(self, p):
if p.name and 'HEXIWEAR' in p.name and not self.peripheral:
self.peripheral = p
print('Connecting to Hexiwear...')
cb.connect_peripheral(p)
def did_connect_peripheral(self, p):
print('Connected:', p.name)
print('Discovering services...')
p.discover_services()
def did_discover_services(self, p, error):
print('did_discover_services({})'.format(p.name))
cb.get_state()
print("Name:", p.name)
print("UUID:", p.uuid)
try:
state = 'Disconnected Connecting Connected'.split()[p.state]
except IndexError:
state = 'Invalid state ({})'.format(p.state)
print("STAT: ", state)
time.sleep(0.4)
print("AUTH:", cb.CH_PROP_AUTHENTICATED_SIGNED_WRITES)
time.sleep(0.4)
print("Properties:", cb.CH_PROP_EXTENDED_PROPERTIES)
time.sleep(0.4)
print("Indicate:", cb.CH_PROP_INDICATE)
time.sleep(0.4)
print("Encryption:", cb.CH_PROP_NOTIFY_ENCRYPTION_REQUIRED)
time.sleep(0.4)
print("{} Services:".format(len(p.services)))
for s in p.services:
print("-" + str(s.uuid))
p.discover_characteristics(s)
def did_discover_characteristics(self, s, error):
print("{} Characteristics:".format(len(s.characteristics)))
for c in s.characteristics:
print("-" + str(c.uuid))
def did_fail_to_connect_peripheral(self, p, error):
print('Failed to connect: %s' % (error,))
def did_disconnect_peripheral(self, p, error):
print('Disconnected, error: %s' % (error,))
self.peripheral = None
mngr = HexiwearManager()
cb.set_central_delegate(mngr)
print('Scanning for Hexiwear...')
cb.scan_for_peripherals()
try:
while True: pass
except KeyboardInterrupt:
cb.reset() ```
Well almost now I am getting just the first characteristic of each service but getting closer.
Thx a bunch!
I just can’t get access to the other services
Thx for the help guys...
Need some help with access to BLE services & characteristics with the Hexiwear dev platformpje !?
from __future__ import print_function
import cb
import sound
import time
import struct
import console
console.set_color(0, 0, 1)
print("""
_ _ _____ _
| || |___ _ _ * | __ | |_ _ ___
| -- | -_| \/ | | __ -| | | | -_|
|_||_|___|_/\__|_ _____|_|___|___|
""")
console.set_color()
class HeartRateManager (object):
def __init__(self):
self.peripheral = None
def did_discover_peripheral(self, p):
if p.name and 'HEXIWEAR' in p.name and not self.peripheral:
self.peripheral = p
print('Connecting to Hexiwear...')
cb.connect_peripheral(p)
def did_connect_peripheral(self, p):
print('Connected:', p.name)
print('Discovering services...')
p.discover_services()
def did_discover_services(self, p, error):
print('did_discover_services({})'.format(p.name))
cb.get_state()
print("Name:", p.name)
print("UUID:", p.uuid)
try:
state = 'Disconnected Connecting Connected'.split()[p.state]
except IndexError:
state = 'Invalid state ({})'.format(p.state)
print("STAT: ", state)
time.sleep(0.4)
print("AUTH:", cb.CH_PROP_AUTHENTICATED_SIGNED_WRITES)
time.sleep(0.4)
print("Properties:", cb.CH_PROP_EXTENDED_PROPERTIES)
time.sleep(0.4)
print("Indicate:", cb.CH_PROP_INDICATE)
time.sleep(0.4)
print("Encryption:", cb.CH_PROP_NOTIFY_ENCRYPTION_REQUIRED)
time.sleep(0.4)
print("{} Services:".format(len(p.services)))
for s in p.services:
print("-" + str(s.uuid))
p.discover_characteristics(s)
def did_discover_characteristics(self, s, error):
print("Characteristics:")
for c in s.characteristics:
print("-" + str(c.uuid))
# s.set_notify_value(c, True)
s.read_characteristic_value(c)
data = s.read_characteristic_value(c)
print(c.value, data)
def did_write_value(self, c, error):
print(self.peripheral.properties)
time.sleep(0.5)
def did_update_value(self, c, error):
time.sleep(0.5)
def did_fail_to_connect_peripheral(self, p, error):
print('Failed to connect: %s' % (error,))
def did_disconnect_peripheral(self, p, error):
print('Disconnected, error: %s' % (error,))
self.peripheral = None
mngr = HeartRateManager()
cb.set_central_delegate(mngr)
print('Scanning for Hexiwear...')
cb.scan_for_peripherals()
try:
while True: pass
except KeyboardInterrupt:
cb.reset()
Can’t get access to all characteristics need some pointers!?
Thx in advance
@mikael Yes thx for pointing that out to me did so and is so much better👍🏻
How can i prefill a textfield with strings and variables combined?
This code gets me an expected string error:
if delta.degrees < 0:
sometext = ('B:', int(delta.degrees + 360), 'D:', int(delta.magnitude))
else:
sometext = ('B:', int(delta.degrees), 'D:', int(delta.magnitude))
tv['textfield1'].text = sometext
What am i doing wrong?
@ccc
Ok thx for pointing that out to me i will chance it.👍🏻
Ok no worries Bumbo i am also a beginner in python and it is a great code language.
Its easy to read and understand and with a great communitie very helpfull.
I managed to create something awesome and usefull in a short time thx to that.
I'll show you my progress so you can see:
import math
import ui
import console
import photos
import matplotlib.pyplot as plt
import numpy as np
from io import BytesIO
class Vector(list):
abs_tol = 1e-10
def __init__(self, *args, **kwargs):
x = kwargs.pop('x', None)
y = kwargs.pop('y', None)
if x and y:
self.append(x)
self.append(y)
elif len(args) == 2:
self.append(args[0])
self.append(args[1])
else:
super().__init__(*args, **kwargs)
@property
def x(self):
''' x component of the vector. '''
return self[0]
@x.setter
def x(self, value):
self[0] = value
@property
def y(self):
''' y component of the vector. '''
return self[1]
@y.setter
def y(self, value):
self[1] = value
def __eq__(self, other):
return math.isclose(
self[0], other[0], abs_tol=self.abs_tol) and math.isclose(
self[1], other[1], abs_tol=self.abs_tol)
def __ne__(self, other):
return not self.__eq__(other)
def __abs__(self):
return type(self)(abs(self.x), abs(self.y))
def __int__(self):
return type(self)(int(self.x), int(self.y))
def __add__(self, other):
return type(self)(self.x + other.x, self.y + other.y)
def __iadd__(self, other):
self.x += other.x
self.y += other.y
return self
def __sub__(self, other):
return type(self)(self.x - other.x, self.y - other.y)
def __mul__(self, other):
return type(self)(self.x * other, self.y * other)
def __truediv__(self, other):
return type(self)(self.x / other, self.y / other)
def __len__(self):
return self.magnitude
def __round__(self):
return type(self)(round(self.x), round(self.y))
def dot_product(self, other):
''' Sum of multiplying x and y components with the x and y components of another vector. '''
return self.x * other.x + self.y * other.y
def distance_to(self, other):
''' Linear distance between this vector and another. '''
return (Vector(other) - self).magnitude
@property
def magnitude(self):
''' Length of the vector, or distance from (0,0) to (x,y). '''
return math.hypot(self.x, self.y)
@magnitude.setter
def magnitude(self, m):
r = self.radians
self.polar(r, m)
@property
def radians(self):
''' Angle between the positive x axis and this vector, in radians. '''
#return round(math.atan2(self.y, self.x), 10)
return math.atan2(self.y, self.x)
@radians.setter
def radians(self, r):
m = self.magnitude
self.polar(r, m)
def polar(self, r, m):
''' Set vector in polar coordinates. `r` is the angle in radians, `m` is vector magnitude or "length". '''
self.y = math.sin(r) * m
self.x = math.cos(r) * m
@property
def degrees(self):
''' Angle between the positive x axis and this vector, in degrees. '''
return math.degrees(self.radians)
@degrees.setter
def degrees(self, d):
self.radians = math.radians(d)
def steps_to(self, other, step_magnitude=1.0):
""" Generator that returns points on the line between this and the other point, with each step separated by `step_magnitude`. Does not include the starting point. """
if self == other:
yield other
else:
step_vector = other - self
steps = math.floor(step_vector.magnitude / step_magnitude)
step_vector.magnitude = step_magnitude
current_position = Vector(self)
for _ in range(steps):
current_position += step_vector
yield Vector(current_position)
if current_position != other:
yield other
def rounded_steps_to(self, other, step_magnitude=1.0):
''' As `steps_to`, but returns points rounded to the nearest integer. '''
for step in self.steps_to(other):
yield round(step)
bearingblue = int(input("Bearing blue: "))
rangeblue = int(input("Range blue: "))
bearingred = int(input("Bearing red: "))
rangered = int(input("Range red: "))
blue = Vector(rangeblue, 0)
blue.degrees = bearingblue
red = Vector(rangered, 0)
red.degrees = bearingred
delta = red - blue
way = np.loadtxt('waypoints.txt')
ways = way[:, 0]
r = way[:, 1]
if delta.degrees < 0:
print('Bearing: ', int(delta.degrees + 360))
print('Distance:', int(delta.magnitude))
else:
print('Bearing: ', int(delta.degrees))
print('Distance:', int(delta.magnitude))
thetablue= np.deg2rad(bearingblue)
thetared= np.deg2rad(bearingred)
thetawayp= np.deg2rad(ways)
class PathView(ui.View):
def __init__(self, frame):
self.frame = frame
self.flex = 'WH'
self.path = None
self.action = None
def touch_began(self, touch):
x, y = touch.location
self.path = ui.Path()
self.path.line_width = 1
self.path.line_join_style = ui.LINE_JOIN_ROUND
self.path.line_cap_style = ui.LINE_CAP_ROUND
self.path.move_to(x, y)
def touch_moved(self, touch):
x, y = touch.location
self.path.line_to(x, y)
self.set_needs_display()
def touch_ended(self, touch):
# Send the current path to the SketchView:
if callable(self.action):
self.action(self)
# Clear the view (the path has now been rendered
# into the SketchView's image view):
self.path = None
self.set_needs_display()
def draw(self):
if self.path:
self.path.stroke()
ax = plt.subplot(111, projection='polar')
plt.polar(thetawayp, r)
plt.polar(thetawayp, r, 'k.', zorder=3)
ax.scatter(thetablue,rangeblue)
ax.scatter(thetared,rangered, color='r')
ax.set_theta_direction(-1)
ax.set_rmax(120)
ax.set_theta_zero_location('N')
ax.set_title("N ", va='bottom')
ax.grid(True)
b = BytesIO()
plt.savefig(b)
class SketchView(ui.View):
def __init__(self, width=768, height=768):
self.bg_color = '#ffffff'
iv = ui.ImageView(frame=(0, 0, width, height))
bg = ui.Image.from_data(b.getvalue())
iv.image = bg
iv.content_mode = ui.CONTENT_SCALE_ASPECT_FILL
image_view = ui.ImageView()
image_view.image = ui.Image.named('Bullseye.png')
image_view.present()
pv = PathView(frame=self.bounds)
pv.action = self.path_action
self.add_subview(iv)
self.add_subview(pv)
blue_button = ui.ButtonItem()
blue_button.title = 'Bluebulls'
blue_button.action = self.bluebulls_action
red_button = ui.ButtonItem()
red_button.title = 'Redbulls'
red_button.tint_color = '#990000'
red_button.action = self.redbulls_action
maps_button = ui.ButtonItem()
maps_button.title = 'Maps'
maps_button.tint_color = '#000d99'
maps_button.action = self.map_action
save_button = ui.ButtonItem()
save_button.title = 'Save Image'
save_button.action = self.save_action
plot_button = ui.ButtonItem()
plot_button.title = 'Plot'
plot_button.tint_color = '#000d99'
plot_button.action = self.plot_action
clear_button = ui.ButtonItem()
clear_button.title = 'Clear'
clear_button.tint_color = '#af0000'
clear_button.action = self.clear_action
self.right_button_items = [save_button, plot_button, red_button]
self.left_button_items = [clear_button, maps_button, blue_button]
self.image_view = iv
def map_action(self, sender):
# Show an image picker dialog (allowing multiple selection) and print the result
assets = photos.pick_asset(title='Pick a Map', multi=True)
def path_action(self, sender):
path = sender.path
old_img = self.image_view.image
width, height = 768, 768
with ui.ImageContext(width, height) as ctx:
if old_img:
old_img.draw()
path.stroke()
self.image_view.image = ctx.get_image()
def redbulls_action(self, sender):
m=1
def bluebulls_action(self, sender):
m=1
def plot_action(self, sender):
self.image_view.image = ui.Image.from_data(b.getvalue())
def clear_action(self, sender):
self.image_view.image = None
def save_action(self, sender):
if self.image_view.image:
# We draw a new image here, so that it has the current
# orientation (the canvas is quadratic).
with ui.ImageContext(self.width, self.height) as ctx:
self.image_view.image.draw()
img = ctx.get_image()
photos.save_image(img)
console.hud_alert('Saved')
else:
console.hud_alert('No Image', 'error')
sv = SketchView()
sv.name = 'BullseyePad'
sv.present()
Its starting to look like an useable app already👍🏻
I am looking into API's right Now not so hard to use and lots of them look it up.
Maybe you can find a nice project for u with the use of API's
Goodluck finding a Nice project!
Next problem😅
Manager to integrate the plot into sketch.py.
But i need to constrain the placing of the plot image.
It jumps to the right halfway out the screen soon as drawing starts
'''
A very simple drawing 'app' that demonstrates
custom views and saving images to the camera roll.
'''
import ui
import photos
import console
import matplotlib.pyplot as plt
import numpy as np
from io import BytesIO
# The PathView class is responsible for tracking
# touches and drawing the current stroke.
# It is used by SketchView.
class PathView (ui.View):
def __init__(self, frame):
self.frame = frame
self.flex = 'WH'
self.path = None
self.action = None
def touch_began(self, touch):
x, y = touch.location
self.path = ui.Path()
self.path.line_width = 1
self.path.line_join_style = ui.LINE_JOIN_ROUND
self.path.line_cap_style = ui.LINE_CAP_ROUND
self.path.move_to(x, y)
def touch_moved(self, touch):
x, y = touch.location
self.path.line_to(x, y)
self.set_needs_display()
def touch_ended(self, touch):
# Send the current path to the SketchView:
if callable(self.action):
self.action(self)
# Clear the view (the path has now been rendered
# into the SketchView's image view):
self.path = None
self.set_needs_display()
def draw(self):
if self.path:
self.path.stroke()
data = np.loadtxt('waypoints.txt')
theta = data[:, 0]
r = data[:, 1]
ax = plt.subplot(111, projection='polar')
plt.polar (theta, r)
ax.set_theta_direction(-1)
ax.set_rmax(120)
ax.set_theta_zero_location('N')
ax.set_title("", va='bottom')
b = BytesIO()
plt.savefig(b)
bg = ui.Image.from_data(b.getvalue())
"""
img_view = ui.ImageView(background_color='white')
img_view.content_mode = ui.CONTENT_SCALE_ASPECT_FIT
img_view.image = bg
img_view.present()
"""
# The main SketchView contains a PathView for the current
# line and an ImageView for rendering completed strokes.
# It also manages the 'Clear' and 'Save' ButtonItems that
# are shown in the title bar.
class SketchView (ui.View):
def __init__(self, width=1024, height=1024):
self.bg_color = 'white'
iv = ui.ImageView(frame=(0, 0, width, height))
iv.image = bg
iv.content_mode = ui.CONTENT_SCALE_ASPECT_FIT
pv = PathView(frame=self.bounds)
pv.action = self.path_action
self.add_subview(iv)
self.add_subview(pv)
save_button = ui.ButtonItem()
save_button.title = 'Save Image'
save_button.action = self.save_action
clear_button = ui.ButtonItem()
clear_button.title = 'Clear'
clear_button.tint_color = 'red'
clear_button.action = self.clear_action
self.right_button_items = [save_button, clear_button]
self.image_view = iv
def path_action(self, sender):
path = sender.path
old_img = self.image_view.image
width, height = self.image_view.width, self.image_view.height
with ui.ImageContext(width, height) as ctx:
if old_img:
old_img.draw()
path.stroke()
self.image_view.image = ctx.get_image()
def clear_action(self, sender):
self.image_view.image = None
def save_action(self, sender):
if self.image_view.image:
# We draw a new image here, so that it has the current
# orientation (the canvas is quadratic).
with ui.ImageContext(self.width, self.height) as ctx:
self.image_view.image.draw()
img = ctx.get_image()
photos.save_image(img)
console.hud_alert('Saved')
else:
console.hud_alert('No Image', 'error')
# We use a square canvas, so that the same image
# can be used in portrait and landscape orientation.
w, h = ui.get_screen_size()
canvas_size = max(w, h)
sv = SketchView(canvas_size, canvas_size)
sv.name = 'Sketch'
sv.present('fullscreen')
Yeah it is steep learning for me atm and format is also one of those things i need to learn.
Also i was fiddling around in that code so much to make it work that format got messed.
My textfile is just as your two coloms sep. by one space still use the same now.
18 50
17 60
15 40
12 40
18 50
Thx again guys i'm not troubleling any more brain with that monster of a code.
Solved it with numpy
So much easier😎
import matplotlib.pyplot as plt
import numpy as np
data = np.loadtxt('waypoints.txt')
theta = data[:, 0]
r = data[:, 1]
ax = plt.subplot(111, projection='polar')
plt.polar (theta, r)
ax.set_theta_direction(-1)
ax.set_rmax(120)
ax.set_theta_zero_location('N')
ax.set_title("Plot", va='bottom')
plt.show()
Hi stephen thx for helping me out with this m8!!!
I have very little coding experience python is the deepest ever.
But i figured it is most easy to get into and figure out and commonly used.
Implemented your corrections but sadly still errors cant convert string to flaot this time in 10
I think maybe my pythonista installment is corrupted cause it does run with you
import matplotlib.pyplot as plt
bearings = list() # changed bearing ⇒ bearings
ranges = list() # changed range ⇒ ranges
lines = [line.rstrip('\n') for line in open('waypoints.txt')]
for line in lines:
# changed str.split(line, " ") ⇒ line.split(" ")
stringElement = line.split(" ")
# Added float parse before int
bearing = int(float(stringElement[0]))
# Added float parse before int
range = int(float(stringElement[1]))
# changed bearing ⇒ bearings
bearings.append(bearing)
# changed range ⇒ ranges
ranges.append(range)
ax = plt.subplot(111, projection='polar')
#Plot points
plt.polar(bearings, ranges, 'k.', zorder=3)
#Plot lines
#plt.polar(bearings, ranges)
ax.set_theta_direction(-1)
ax.set_rmax(120)
ax.set_theta_zero_location('N')
ax.set_title("Plot", va='bottom')
plt.show()
Hmmm closer but Now i get a sintax error strangly onlusten in line 9😩
I can't seem to find out what the error is about in line 8 & 9
Invalid literal for int() with base 10?
import matplotlib.pyplot as plt
bearing = list()
range = list()
lines = [line.rstrip('\n') for line in open('waypoints.txt')]
for line in lines:
stringElement = str.split(line, " ")
bearing = int(stringElement[0])
range = int(stringElement[1])
bearing.append(bearing)
range.append(range)
ax = plt.subplot(111, projection='polar')
#Plot points
plt.polar(bearings, ranges)
#Plot lines
#plt.polar(bearings, ranges)
ax.set_theta_direction(-1)
ax.set_rmax(120)
ax.set_theta_zero_location('N')
ax.set_title("Plot", va='bottom')
plt.show()
What am i doping wrong here?
Thx in advance for the help!
Regards,
Robert.
Hi maybe you can help me with this one?
I am trying to put together a tactical kneepad tool for virtual fighter pilots.
It helps with situational awareness concrening bullseye BRAA calls in game.
This is what i got so far and should work out of the box so you can check it out:
import matplotlib.pyplot as plt
import numpy as np
import math
class Vector (list):
''' Simple 2D vector class to make vector operations more convenient. If
performance is a concern, you are probably better off looking at numpy.
Supports the following operations:
* Initialization from two arguments, two keyword arguments (`x` and `y`),
tuple, list, or another Vector.
* Equality and unequality comparisons to other vectors. For floating point
numbers, equality tolerance is 1e-10.
* `abs`, `int` and `round`
* Addition and in-place addition
* Subtraction
* Multiplication and division by a scalar
* `len`, which is the same as `magnitude`, see below.
Sample usage:
v = Vector(x = 1, y = 2)
v2 = Vector(3, 4)
v += v2
assert str(v) == '[4, 6]'
assert v / 2.0 == Vector(2, 3)
assert v * 0.1 == Vector(0.4, 0.6)
assert v.distance_to(v2) == math.sqrt(1+4)
v3 = Vector(Vector(1, 2) - Vector(2, 0)) # -1.0, 2.0
v3.magnitude *= 2
assert v3 == [-2, 4]
v3.radians = math.pi # 180 degrees
v3.magnitude = 2
assert v3 == [-2, 0]
v3.degrees = -90
assert v3 == [0, -2]
'''
abs_tol = 1e-10
def __init__(self, *args, **kwargs):
x = kwargs.pop('x', None)
y = kwargs.pop('y', None)
if x and y:
self.append(x)
self.append(y)
elif len(args) == 2:
self.append(args[0])
self.append(args[1])
else:
super().__init__(*args, **kwargs)
@property
def x(self):
''' x component of the vector. '''
return self[0]
@x.setter
def x(self, value):
self[0] = value
@property
def y(self):
''' y component of the vector. '''
return self[1]
@y.setter
def y(self, value):
self[1] = value
def __eq__(self, other):
return math.isclose(self[0], other[0], abs_tol=self.abs_tol) and math.isclose(self[1], other[1], abs_tol=self.abs_tol)
def __ne__(self, other):
return not self.__eq__(other)
def __abs__(self):
return type(self)(abs(self.x), abs(self.y))
def __int__(self):
return type(self)(int(self.x), int(self.y))
def __add__(self, other):
return type(self)(self.x + other.x, self.y + other.y)
def __iadd__(self, other):
self.x += other.x
self.y += other.y
return self
def __sub__(self, other):
return type(self)(self.x - other.x, self.y - other.y)
def __mul__(self, other):
return type(self)(self.x * other, self.y * other)
def __truediv__(self, other):
return type(self)(self.x / other, self.y / other)
def __len__(self):
return self.magnitude
def __round__(self):
return type(self)(round(self.x), round(self.y))
def dot_product(self, other):
''' Sum of multiplying x and y components with the x and y components of another vector. '''
return self.x * other.x + self.y * other.y
def distance_to(self, other):
''' Linear distance between this vector and another. '''
return (Vector(other) - self).magnitude
@property
def magnitude(self):
''' Length of the vector, or distance from (0,0) to (x,y). '''
return math.hypot(self.x, self.y)
@magnitude.setter
def magnitude(self, m):
r = self.radians
self.polar(r, m)
@property
def radians(self):
''' Angle between the positive x axis and this vector, in radians. '''
#return round(math.atan2(self.y, self.x), 10)
return math.atan2(self.y, self.x)
@radians.setter
def radians(self, r):
m = self.magnitude
self.polar(r, m)
def polar(self, r, m):
''' Set vector in polar coordinates. `r` is the angle in radians, `m` is vector magnitude or "length". '''
self.y = math.sin(r) * m
self.x = math.cos(r) * m
@property
def degrees(self):
''' Angle between the positive x axis and this vector, in degrees. '''
return math.degrees(self.radians)
@degrees.setter
def degrees(self, d):
self.radians = math.radians(d)
def steps_to(self, other, step_magnitude=1.0):
""" Generator that returns points on the line between this and the other point, with each step separated by `step_magnitude`. Does not include the starting point. """
if self == other:
yield other
else:
step_vector = other - self
steps = math.floor(step_vector.magnitude/step_magnitude)
step_vector.magnitude = step_magnitude
current_position = Vector(self)
for _ in range(steps):
current_position += step_vector
yield Vector(current_position)
if current_position != other:
yield other
def rounded_steps_to(self, other, step_magnitude=1.0):
''' As `steps_to`, but returns points rounded to the nearest integer. '''
for step in self.steps_to(other):
yield round(step)
bearingblue = int(input("Bearing blue:"))
rangeblue = int(input("Range blue:"))
bearingred = int(input("Bearing red:"))
rangered = int(input("Range red:"))
blue = Vector(rangeblue, 0)
blue.degrees = bearingblue
red = Vector(rangered, 0)
red.degrees = bearingred
delta = red - blue
print('Distance:', delta.magnitude)
print('Bearing:', delta.degrees)
thetablue= np.deg2rad(bearingblue)
thetared= np.deg2rad(bearingred)
fig = plt.figure()
ax = fig.add_subplot(111, projection='polar')
ax.scatter(thetablue,rangeblue)
ax.scatter(thetared,rangered, color='r')
ax.set_theta_direction(-1)
"""ax.set_rmax(120)"""
ax.set_theta_zero_location('N')
ax.set_title("Plot", va='bottom')
plt.show()
What i want to do next is integrate this into something like sketch.py demo.
To make it possible to draw things onto like flightpath & annotations etc.
Also the feature of exporting as img is handy for recap and debriefing.
Take a look maybe you like this project.
Regards,
Robert.
Sorry for my noobisme but this is my first time coding python.
I trying to integrate the above code into sketch.py demo code below.
I can't get it to be printed & plotted into (ui.View) so i can draw onto it.
'''
A very simple drawing 'app' that demonstrates
custom views and saving images to the camera roll.
'''
import ui
import photos
import console
import matplotlib.pyplot as plt
import numpy as np
from vector import Vector
# The PathView class is responsible for tracking
# touches and drawing the current stroke.
# It is used by SketchView.
class PathView (ui.View):
def __init__(self, frame):
self.frame = frame
self.flex = 'WH'
self.path = None
self.action = None
def touch_began(self, touch):
x, y = touch.location
self.path = ui.Path()
self.path.line_width = 1
self.path.line_join_style = ui.LINE_JOIN_ROUND
self.path.line_cap_style = ui.LINE_CAP_ROUND
self.path.move_to(x, y)
def touch_moved(self, touch):
x, y = touch.location
self.path.line_to(x, y)
self.set_needs_display()
def touch_ended(self, touch):
# Send the current path to the SketchView:
if callable(self.action):
self.action(self)
# Clear the view (the path has now been rendered
# into the SketchView's image view):
self.path = None
self.set_needs_display()
def draw(self):
if self.path:
self.path.stroke()
# The main SketchView contains a PathView for the current
# line and an ImageView for rendering completed strokes.
# It also manages the 'Clear' and 'Save' ButtonItems that
# are shown in the title bar.
class SketchView (ui.View):
def __init__(self, width=1024, height=1024):
self.bg_color = 'white'
iv = ui.ImageView(frame=(0, 0, width, height))
pv = PathView(frame=self.bounds)
pv.action = self.path_action
self.add_subview(iv)
self.add_subview(pv)
save_button = ui.ButtonItem()
save_button.title = 'Save Image'
save_button.action = self.save_action
clear_button = ui.ButtonItem()
clear_button.title = 'Clear'
clear_button.tint_color = 'red'
clear_button.action = self.clear_action
self.right_button_items = [save_button, clear_button]
self.image_view = iv
def path_action(self, sender):
path = sender.path
old_img = self.image_view.image
width, height = self.image_view.width, self.image_view.height
with ui.ImageContext(width, height) as ctx:
if old_img:
old_img.draw()
path.stroke()
self.image_view.image = ctx.get_image()
def clear_action(self, sender):
self.image_view.image = None
def save_action(self, sender):
if self.image_view.image:
# We draw a new image here, so that it has the current
# orientation (the canvas is quadratic).
with ui.ImageContext(self.width, self.height) as ctx:
self.image_view.image.draw()
img = ctx.get_image()
photos.save_image(img)
console.hud_alert('Saved')
else:
console.hud_alert('No Image', 'error')
#---------------------------------------integrate into sketch.py
bearingblue = int(input("Bearing blue:"))
rangeblue = int(input("Range blue:"))
bearingred = int(input("Bearing red:"))
rangered = int(input("Range red:"))
blue = Vector(rangeblue, 0)
blue.degrees = bearingblue
red = Vector(rangered, 0)
red.degrees = bearingred
delta = red - blue
print('Distance:', delta.magnitude)
print('Bearing:', delta.degrees)
thetablue= np.deg2rad(bearingblue)
thetared= np.deg2rad(bearingred)
fig = plt.figure()
ax = fig.add_subplot(111, projection='polar')
ax.scatter(thetablue,rangeblue)
ax.scatter(thetared,rangered, color='r')
ax.set_theta_direction(-1)
"""ax.set_rmax(120)"""
ax.set_theta_zero_location('N')
ax.set_title("Plot", va='bottom')
plt.show()
#--------------------------------------------
# We use a square canvas, so that the same image
# can be used in portrait and landscape orientation.
w, h = ui.get_screen_size()
canvas_size = max(w, h)
sv = SketchView(canvas_size, canvas_size)
sv.name = 'Sketch'
sv.present('fullscreen')
Do i need to make it a class to be able to do this?
Thx in advance for any pointers.
Regards,
Robert.
Works like a charm thx for the help guys!!
Just need to round and substract negatieve degrees from 360.
But thats easy...😎👍🏻