index int64 | repo_name string | branch_name string | path string | content string | import_graph string |
|---|---|---|---|---|---|
57,254 | tatsunoshirou/mysite | refs/heads/master | /polls/models.py | from django.db import models
# Create your models here.
from django.utils.timezone import now
class Post(models.Model):
name = models.CharField('名前', max_length=32, blank=False)
title = models.CharField('題名', max_length=32, blank=False)
message = models.TextField('投稿内容', max_length=145)
created_at = models.DateTimeField(default=now)
class Meta:
db_table = 'post'
verbose_name = verbose_name_plural = '投稿'
def __str__(self):
return self.title
| {"/polls/views.py": ["/polls/models.py"]} |
57,255 | tatsunoshirou/mysite | refs/heads/master | /polls/views.py | from django.shortcuts import render, redirect
# Create your views here.
from django.http.response import HttpResponseRedirect
from django.template.response import TemplateResponse
from django.http import Http404
from django.urls import reverse
from django.core.paginator import Paginator
from django.contrib.auth.decorators import login_required
from polls.models import Post
from polls.forms import PostForm
def post_list(request):
posts = Post.objects.order_by('-created_at')
paginator = Paginator(posts, 9)
page = request.GET.get('page', 1)
posts = paginator.page(page)
return TemplateResponse(request, 'polls/post_list.html',
{'posts': posts})
def post_detail(request, post_id):
try:
post = Post.objects.get(id=post_id)
except Post.DoesNotExist:
raise Http404
return TemplateResponse(request, 'polls/post_detail.html',
{'post': post})
@login_required()
def index(request):
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('post_list'))
else:
form = PostForm()
posts = Post.objects.order_by('-created_at')
context = {'posts': posts, 'form': form}
return TemplateResponse(request, 'polls/index.html', context)
| {"/polls/views.py": ["/polls/models.py"]} |
57,256 | tatsunoshirou/mysite | refs/heads/master | /polls/urls.py | from django.urls import path
from . import views
urlpatterns = [
path('', views.post_list, name='post_list'),
path('index/', views.index, name='index'),
path('posts/<int:post_id>/', views.post_detail, name='post_detail'),
] | {"/polls/views.py": ["/polls/models.py"]} |
57,257 | tatsunoshirou/mysite | refs/heads/master | /polls/migrations/0003_post_title.py | # Generated by Django 2.1.4 on 2019-01-10 02:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('polls', '0002_auto_20190109_1519'),
]
operations = [
migrations.AddField(
model_name='post',
name='title',
field=models.CharField(default='japan', max_length=32, verbose_name='題名'),
preserve_default=False,
),
]
| {"/polls/views.py": ["/polls/models.py"]} |
57,258 | tatsunoshirou/mysite | refs/heads/master | /polls/migrations/0001_initial.py | # Generated by Django 2.1.4 on 2019-01-09 02:41
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=32, verbose_name='名前')),
('message', models.TextField(max_length=140, verbose_name='メッセージ')),
('created_at', models.DateTimeField(default=django.utils.timezone.now)),
],
options={
'verbose_name': '投稿',
'verbose_name_plural': '投稿',
'db_table': 'post',
},
),
]
| {"/polls/views.py": ["/polls/models.py"]} |
57,259 | rouxcode/django-treebeard-admin | refs/heads/master | /treebeard_admin/admin/admin.py | from __future__ import unicode_literals
import json
try:
from urllib.parse import quote as urlquote
except ImportError:
from django.utils.http import urlquote
from django import forms
from django.conf import settings
from django.conf.urls import url
from django.contrib import admin, messages
from django.contrib.admin.options import IS_POPUP_VAR, TO_FIELD_VAR
from django.contrib.admin.templatetags.admin_urls import add_preserved_filters
from django.utils.html import format_html
from django.http import (
Http404,
HttpResponseBadRequest,
HttpResponseForbidden,
HttpResponseNotAllowed,
HttpResponseRedirect,
JsonResponse,
)
from django.template.response import TemplateResponse
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils.html import mark_safe
from django.utils.translation import ugettext_lazy as _
class TreeAdmin(admin.ModelAdmin):
_node = None
actions = None
max_depth = None # TODO implement that the max_depth gets to the form
change_list_template = 'admin/treebeard_admin/tree_list.html'
change_form_template = 'admin/treebeard_admin/tree_form.html'
delete_confirmation_template = 'admin/treebeard_admin/tree_delete.html'
object_history_template = 'admin/treebeard_admin/tree_history.html'
class Media:
css = {
'all': ['admin/treebeard_admin/css/tree.css']
}
if 'djangocms_admin_style' in settings.INSTALLED_APPS:
css['all'].append('admin/treebeard_admin/css/tree.cms.css')
js = [
# 'admin/treebeard_admin/js/changelist.tree.js',
'admin/treebeard_admin/js/sortable.js',
'admin/treebeard_admin/js/sortable.tree.js',
]
def get_urls(self):
info = [
self.model._meta.app_label,
self.model._meta.model_name,
]
urls = [
# Ajax Views
url(
r'^update/$',
self.admin_site.admin_view(self.update_view),
name='{}_{}_update'.format(*info)
),
# Template Views
url(
r'^(?P<node_id>\d+)/list/$',
self.admin_site.admin_view(self.changelist_view),
name='{}_{}_changelist'.format(*info)
),
url(
r'^(?P<node_id>\d+)/add/$',
self.admin_site.admin_view(self.add_view),
name='{}_{}_add'.format(*info)
),
# url(
# r'^(?P<node_id>\d+)/(?P<object_id>\d+)/change/$',
# self.admin_site.admin_view(self.change_view),
# name='{}_{}_change'.format(*info)
# ),
url(
r'^(?P<node_id>\d+)/(?P<object_id>\d+)/delete/$',
self.admin_site.admin_view(self.delete_view),
name='{}_{}_delete'.format(*info)
),
url(
r'^(?P<node_id>\d+)/(?P<object_id>\d+)/history/$',
self.admin_site.admin_view(self.history_view),
name='{}_{}_history'.format(*info)
),
]
urls += super(TreeAdmin, self).get_urls()
return urls
def get_list_display(self, request):
list_display = ['col_position_node'] + [
d for d in super(TreeAdmin, self).get_list_display(request)
]
list_display.append('col_node_children_count')
# TODO implement move ajax
# list_display.append('col_move_node')
list_display.append('col_edit_node')
list_display.append('col_delete_node')
return list_display
def get_list_display_links(self, request, list_display):
return None
def get_queryset(self, request, fallback=False):
"""
Only display nodes for the current node or with depth = 1 (root)
"""
if fallback:
return super(TreeAdmin, self).get_queryset(request)
if self._node:
qs = self._node.get_children()
else:
depth = 1
qs = super(TreeAdmin, self).get_queryset(request)
qs = qs.filter(depth=depth)
return qs
def get_object(self, request, object_id, from_field=None):
"""
Returns an instance matching the field and value provided, the primary
key is used if no field is provided. Returns ``None`` if no match is
found or the object_id fails validation.
"""
obj = super(TreeAdmin, self).get_object(request, object_id, from_field)
if obj is None:
try:
qs = self.get_queryset(request, fallback=True)
obj = qs.get(pk=object_id)
except self.model.DoesNotExist:
obj = None
return obj
def get_changeform_initial_data(self, request):
data = super(TreeAdmin, self).get_changeform_initial_data(request)
if self._node:
data['_parent_id'] = self._node.id
return data
def get_node(self, node_id):
"""
Get the current root node
"""
if node_id:
qs = self.model._default_manager.get_queryset()
try:
id = int(node_id)
except ValueError:
return None
try:
return qs.get(pk=id)
except self.model.DoesNotExist:
raise Http404(
'{} with id "{}" does not exist'.format(
self.model._meta.model_name,
id
)
)
return None
def add_view(self, request, node_id=None, form_url='', extra_context=None):
self._node = self.get_node(node_id)
extra_context = extra_context or {}
extra_context.update({'parent_node': self._node})
return super(TreeAdmin, self).add_view(
request,
form_url=form_url or self.get_add_url(),
extra_context=extra_context
)
def response_add(self, request, obj, post_url_continue=None):
if not post_url_continue and self._node:
post_url_continue = self.get_change_url(instance=obj)
return super(TreeAdmin, self).response_add(
request,
obj,
post_url_continue=post_url_continue
)
def response_post_save_add(self, request, obj):
"""
Figure out where to redirect after the 'Save' button has been pressed
when adding a new object.
"""
opts = self.model._meta
if self.has_change_permission(request, None):
preserved_filters = self.get_preserved_filters(request)
post_url = add_preserved_filters(
{'preserved_filters': preserved_filters, 'opts': opts},
self.get_changelist_url()
)
else:
post_url = reverse('admin:index', current_app=self.admin_site.name)
return HttpResponseRedirect(post_url)
def change_view(self, request, object_id, form_url='', extra_context=None):
obj = self.get_object(request, object_id)
if obj:
self._node = obj.get_parent()
extra_context = extra_context or {}
extra_context.update({'parent_node': self._node})
return super(TreeAdmin, self).change_view(
request,
object_id,
form_url=form_url,
extra_context=extra_context
)
def response_change(self, request, obj):
"""
Determine the HttpResponse for the change_view stage.
"""
if IS_POPUP_VAR in request.POST:
opts = obj._meta
to_field = request.POST.get(TO_FIELD_VAR)
attr = str(to_field) if to_field else opts.pk.attname
value = request.resolver_match.kwargs['object_id']
new_value = obj.serializable_value(attr)
popup_response_data = json.dumps({
'action': 'change',
'value': str(value),
'obj': str(obj),
'new_value': str(new_value),
})
return TemplateResponse(
request,
self.popup_response_template or [
'admin/{}/{}/popup_response.html'.format(
opts.app_label,
opts.model_name
),
'admin/{}/popup_response.html'.format(opts.app_label),
'admin/popup_response.html',
],
{'popup_response_data': popup_response_data})
opts = self.model._meta
preserved_filters = self.get_preserved_filters(request)
msg_dict = {
'name': opts.verbose_name,
'obj': format_html(
'<a href="{}">{}</a>',
urlquote(request.path),
obj
),
}
if "_continue" in request.POST:
msg = format_html(
_(
'The {name} "{obj}" was changed successfully.'
'You may edit it again below.'
),
**msg_dict
)
self.message_user(request, msg, messages.SUCCESS)
redirect_url = self.get_change_url(instance=obj)
redirect_url = add_preserved_filters(
{'preserved_filters': preserved_filters, 'opts': opts},
redirect_url
)
return HttpResponseRedirect(redirect_url)
elif "_saveasnew" in request.POST:
msg = format_html(
_(
'The {name} "{obj}" was added successfully.'
'You may edit it again below.'
),
**msg_dict
)
self.message_user(request, msg, messages.SUCCESS)
redirect_url = self.get_change_url(instance=obj)
redirect_url = add_preserved_filters(
{'preserved_filters': preserved_filters, 'opts': opts},
redirect_url
)
return HttpResponseRedirect(redirect_url)
elif "_addanother" in request.POST:
msg = format_html(
_(
'The {name} "{obj}" was changed successfully.'
'You may add another {name} below.'
),
**msg_dict
)
self.message_user(request, msg, messages.SUCCESS)
redirect_url = self.get_add_url()
redirect_url = add_preserved_filters(
{'preserved_filters': preserved_filters, 'opts': opts},
redirect_url
)
return HttpResponseRedirect(redirect_url)
else:
msg = format_html(
_('The {name} "{obj}" was changed successfully.'),
**msg_dict
)
self.message_user(request, msg, messages.SUCCESS)
return self.response_post_save_change(request, obj)
def response_post_save_change(self, request, obj):
opts = self.model._meta
if self.has_change_permission(request, None):
preserved_filters = self.get_preserved_filters(request)
post_url = add_preserved_filters(
{'preserved_filters': preserved_filters, 'opts': opts},
self.get_changelist_url()
)
else:
post_url = reverse('admin:index', current_app=self.admin_site.name)
return HttpResponseRedirect(post_url)
def delete_view(self, request, object_id, node_id=None,
extra_context=None):
self._node = self.get_node(node_id)
extra_context = extra_context or {}
extra_context.update({'parent_node': self._node})
return super(TreeAdmin, self).delete_view(
request,
object_id,
extra_context,
)
def response_delete(self, request, obj_display, obj_id):
"""
Determine the HttpResponse for the delete_view stage.
"""
opts = self.model._meta
if IS_POPUP_VAR in request.POST:
popup_response_data = json.dumps({
'action': 'delete',
'value': str(obj_id),
})
return TemplateResponse(
request,
self.popup_response_template or [
'admin/{}/{}/popup_response.html'.format(
opts.app_label,
opts.model_name
),
'admin/{}/popup_response.html'.format(
opts.app_label
),
'admin/popup_response.html',
], {
'popup_response_data': popup_response_data,
}
)
msg = _('The %(name)s "%(obj)s" was deleted successfully.') % {
'name': opts.verbose_name,
'obj': obj_display,
},
self.message_user(request, msg, messages.SUCCESS)
if self.has_change_permission(request, None):
preserved_filters = self.get_preserved_filters(request)
post_url = add_preserved_filters(
{'preserved_filters': preserved_filters, 'opts': opts},
self.get_changelist_url()
)
else:
post_url = reverse('admin:index', current_app=self.admin_site.name)
return HttpResponseRedirect(post_url)
def history_view(self, request, object_id, node_id=None,
extra_context=None):
self._node = self.get_node(node_id)
extra_context = extra_context or {}
extra_context.update({'parent_node': self._node})
return super(TreeAdmin, self).history_view(
request,
object_id,
extra_context
)
def changelist_view(self, request, node_id=None, extra_context=None):
self._node = self.get_node(node_id)
extra_context = extra_context or {}
extra_context.update({
'parent_node': self._node,
'add_url': self.get_add_url(),
'update_url': self.get_update_url(),
'max_depth': self.max_depth or 0,
})
return super(TreeAdmin, self).changelist_view(
request,
extra_context,
)
def get_add_url(self, object_id=None, instance=None):
# TODO this method needs proper error logging
# if there is a reference obj (object_id, instance) use it to get
# the parent node else check if there the path provides a parent
if object_id and not instance:
instance = self.model._default_manager.get(pk=object_id)
if instance:
parent = instance.get_parent()
kwargs = {'node_id': parent.pk}
elif self._node:
kwargs = {'node_id': self._node.pk}
else:
kwargs = None
info = [self.model._meta.app_label, self.model._meta.model_name]
return reverse(
'admin:{}_{}_add'.format(*info),
kwargs=kwargs,
current_app=self.admin_site.name
)
def get_change_url(self, object_id=None, instance=None):
# TODO this method needs proper error logging
# get the parent from the given obj (object_id, instance)
parent = None
opts = self.model._meta
if object_id and not instance:
instance = self.model._default_manager.get(pk=object_id)
if instance:
parent = instance.get_parent()
if parent:
args = None
kwargs = {'object_id': instance.pk, 'node_id': parent.pk}
else:
kwargs = None
args = [instance.pk]
kwargs = None
args = [instance.pk]
return reverse(
'admin:{}_{}_change'.format(opts.app_label, opts.model_name),
args=args,
kwargs=kwargs,
current_app=self.admin_site.name
)
def get_changelist_url(self, object_id=None):
kwargs = None
if object_id:
kwargs = {'node_id': object_id}
elif self._node:
kwargs = {'node_id': self._node.pk}
info = [self.model._meta.app_label, self.model._meta.model_name]
url = reverse(
'admin:{}_{}_changelist'.format(*info),
kwargs=kwargs,
current_app=self.admin_site.name
)
return url
def get_update_url(self):
info = [self.model._meta.app_label, self.model._meta.model_name]
return reverse(
'admin:{}_{}_update'.format(*info),
current_app=self.admin_site.name
)
def update_view(self, request):
if not request.is_ajax() or request.method != 'POST':
return HttpResponseBadRequest('Not an XMLHttpRequest')
if request.method != 'POST':
return HttpResponseNotAllowed('Must be a POST request')
if not self.has_change_permission(request):
return HttpResponseForbidden(
'Missing permissions to perform this request'
)
Form = self.get_update_form_class()
form = Form(request.POST)
if form.is_valid():
data = {'message': 'ok'}
pos = form.cleaned_data.get('pos')
parent = form.cleaned_data.get('parent')
node = form.cleaned_data.get('node')
target = form.cleaned_data.get('target')
if pos == 'first':
if parent:
node.move(parent, pos='first-child')
else:
target = node.get_first_root_node()
node.move(target, pos='left')
elif pos == 'last':
if parent:
node.move(parent, pos='last-child')
else:
target = node.get_last_root_node()
node.move(target, pos='right')
else:
node.move(target, pos=pos)
node = self.model.objects.get(pk=node.pk)
node.save()
else:
data = {
'message': 'error',
'error': _('There seams to be a problem with your list')
}
return JsonResponse(data)
def get_update_form_class(self):
class UpdateForm(forms.Form):
depth = forms.IntegerField()
pos = forms.ChoiceField(
choices=[
('left', 'left'),
('right', 'right'),
('last', 'last'),
('first', 'first'),
]
)
node = forms.ModelChoiceField(
queryset=self.model._default_manager.get_queryset()
)
target = forms.ModelChoiceField(
queryset=self.model._default_manager.get_queryset()
)
parent = forms.ModelChoiceField(
required=False,
queryset=self.model._default_manager.get_queryset()
)
return UpdateForm
def col_position_node(self, obj):
data_attrs = [
'data-pk="{}"'.format(obj.pk),
'data-depth="{}"'.format(obj.depth),
'data-name="{}"'.format(obj),
]
if self._node:
data_attrs.append('data-parent="{}"'.format(self._node.pk))
html = '<span class="treebeard-admin-drag" {}></span>'.format(
' '.join(data_attrs)
)
return mark_safe(html)
col_position_node.short_description = ''
def col_move_node(self, obj):
css_classes = 'icon-button treebeard-admin-icon-button place'
data_attrs = [
'data-pk="{}"'.format(obj.pk),
'data-depth="{}"'.format(obj.depth),
'data-name="{}"'.format(obj),
]
html = '<span class="{}" {}>{}</span>'.format(
css_classes,
' '.join(data_attrs),
render_to_string('admin/svg/icon-move.svg')
)
return mark_safe(html)
col_move_node.short_description = _('Move')
def col_delete_node(self, obj):
info = [self.model._meta.app_label, self.model._meta.model_name]
css_classes = 'icon-button treebeard-admin-icon-button delete'
if self._node:
delete_url = reverse(
'admin:{}_{}_delete'.format(*info),
kwargs={'object_id': obj.pk, 'node_id': self._node.pk},
current_app=self.admin_site.name
)
else:
delete_url = reverse(
'admin:{}_{}_delete'.format(*info),
args=[obj.pk],
current_app=self.admin_site.name
)
html_data_attrs = 'data-id="{}" data-delete-url="{}"'.format(
obj.id,
delete_url
)
html = '<a class="{}" href="{}" {}>{}</a>'.format(
css_classes,
delete_url,
html_data_attrs,
render_to_string('admin/svg/icon-delete.svg')
)
return mark_safe(html)
col_delete_node.short_description = _('Delete')
def col_edit_node(self, obj):
css_classes = 'icon-button treebeard-admin-icon-button edit'
url_edit = self.get_change_url(instance=obj)
url_list = self.get_changelist_url(obj.id)
data_attrs = [
'data-id="{}"'.format(obj.id),
'data-edit-url="{}"'.format(url_edit),
'data-list-url="{}"'.format(url_list),
]
html = '<a class="{}" href="{}" {}>{}</a>'.format(
css_classes,
url_edit,
' '.join(data_attrs),
render_to_string('admin/svg/icon-edit.svg')
)
return mark_safe(html)
col_edit_node.short_description = _('Edit')
def col_node_children_count(self, obj):
html = '{}'.format(obj.get_children_count())
return mark_safe(html)
col_node_children_count.short_description = _('Children')
class TreeAdminWithSideTree(TreeAdmin):
pass
| {"/treebeard_admin/admin/__init__.py": ["/treebeard_admin/admin/admin.py", "/treebeard_admin/admin/forms.py"]} |
57,260 | rouxcode/django-treebeard-admin | refs/heads/master | /treebeard_admin/admin/forms.py | from __future__ import unicode_literals
from django import forms
from django.db.models.query import QuerySet
from django.forms.models import modelform_factory
from django.utils.html import escape
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from treebeard.forms import _get_exclude_for_model
class TreeAdminForm(forms.ModelForm):
max_depth = None
_position_choices = (
('last-child', _('At the bottom')),
('first-child', _('At the top')),
)
_parent_id = forms.TypedChoiceField(
coerce=int,
label=_('Parent node'),
)
_position = forms.ChoiceField(
choices=_position_choices,
initial=_position_choices[0][0],
label=_('Position'),
required=False,
)
def __init__(self, *args, **kwargs):
instance = kwargs.get('instance')
self.declared_fields['_parent_id'].choices = self.mk_dropdown_tree(
self._meta.model,
for_node=kwargs.get('instance', None)
)
if instance:
parent = instance.get_parent()
if parent:
self.declared_fields['_parent_id'].initial = parent.pk
else:
self.declared_fields['_parent_id'].initial = 0
super(TreeAdminForm, self).__init__(*args, **kwargs)
def _clean_cleaned_data(self):
"""
delete auxilary fields not belonging to node model
"""
parent_id = self.cleaned_data.get('_parent_id', None)
try:
del self.cleaned_data['_parent_id']
except KeyError:
pass
default = self._position_choices[0][0]
position = self.cleaned_data.get('_position') or default
try:
del self.cleaned_data['_position']
except KeyError:
pass
return parent_id, position
def _get_parent(self, pk=None):
if not pk:
return None
model = self._meta.model
try:
parent = self._meta.model.objects.get(pk=pk)
except model.DoesNotExist:
return None
return parent
def _get_creation_data(self):
data = {}
for field in self.cleaned_data:
if not isinstance(self.cleaned_data[field], (list, QuerySet)):
data[field] = self.cleaned_data[field]
return data
def save(self, commit=True):
parent_id, position = self._clean_cleaned_data()
if self.instance.pk is None:
data = self._get_creation_data()
parent = self._get_parent(pk=parent_id)
if parent:
self.instance = parent.add_child(**data)
self.instance.move(parent, pos=position)
else:
self.instance = self._meta.model.add_root(**data)
if position == 'first-child':
self.instance.move(parent, pos=position)
else:
parent = self.instance.get_parent()
self.instance.save()
# If the parent_id changed move the node to the new parent
if not parent_id == getattr(parent, 'pk', 0):
try:
new_parent = self._meta.model.objects.get(pk=parent_id)
except self._meta.model.DoesNotExist:
new_parent = self._meta.model.get_last_root_node()
position = 'right'
self.instance.move(new_parent, position)
# Reload the instance
self.instance = self._meta.model.objects.get(pk=self.instance.pk)
super(TreeAdminForm, self).save(commit=commit)
return self.instance
@staticmethod
def is_loop_safe(for_node, possible_parent):
if for_node is not None:
return not (
possible_parent == for_node
) or (
possible_parent.is_descendant_of(for_node)
)
return True
@staticmethod
def mk_indent(level):
return ' ' * (level - 1)
@classmethod
def add_subtree(cls, for_node, node, options):
"""
Recursively build options tree.
"""
# If max_depth is set limit the subtree rendering
if not cls.max_depth or node.depth <= cls.max_depth:
if cls.is_loop_safe(for_node, node):
options.append(
(
node.pk,
mark_safe(
cls.mk_indent(node.get_depth()) + escape(node)
)
)
)
for subnode in node.get_children():
cls.add_subtree(for_node, subnode, options)
@classmethod
def mk_dropdown_tree(cls, model, for_node=None):
"""
Creates a tree-like list of choices
"""
options = [(0, _('-- root --'))]
for node in model.get_root_nodes():
cls.add_subtree(for_node, node, options)
return options
def movenodeform_factory(model, form=TreeAdminForm, exclude=None, **kwargs):
tree_exclude = _get_exclude_for_model(model, exclude)
return modelform_factory(model, form=form, exclude=tree_exclude, **kwargs)
| {"/treebeard_admin/admin/__init__.py": ["/treebeard_admin/admin/admin.py", "/treebeard_admin/admin/forms.py"]} |
57,261 | rouxcode/django-treebeard-admin | refs/heads/master | /treebeard_admin/admin/__init__.py | from __future__ import unicode_literals
from .admin import TreeAdmin
from .forms import TreeAdminForm, movenodeform_factory
__all__ = [
TreeAdmin,
TreeAdminForm,
movenodeform_factory
]
| {"/treebeard_admin/admin/__init__.py": ["/treebeard_admin/admin/admin.py", "/treebeard_admin/admin/forms.py"]} |
57,263 | HCI902E18/inputz | refs/heads/master | /inputz/logging/Logger.py | import logging
from logging import getLogger
class Logger(object):
"""
Logger
This class is a libary made for easy and uniform implementation of logging.
"""
def __init__(self):
logging.basicConfig(
format='[%(name)s][%(levelname)s]: %(message)s'
)
self.log = getLogger(self.__class__.__name__)
# self.log.setLevel(DEBUG)
self.log.setLevel(logging.INFO)
| {"/inputz/keys/Joystick.py": ["/inputz/Input.py"], "/examples/XboxController.py": ["/inputz/Devices.py"], "/inputz/__init__.py": ["/inputz/Controller.py", "/inputz/Devices.py", "/inputz/Input.py", "/inputz/invokations/Invokation.py", "/inputz/KillableThread.py", "/inputz/OS.py"], "/examples/EmbedClassTest.py": ["/inputz/Devices.py"], "/inputz/handlers/Contentious.py": ["/inputz/handlers/Handler.py"], "/inputz/controllers/XboxController.py": ["/inputz/Controller.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/OS.py", "/inputz/keys/__init__.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/examples/ClassTest.py": ["/inputz/Devices.py"], "/inputz/keys/__init__.py": ["/inputz/keys/Trigger.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/inputz/handlers/Single.py": ["/inputz/handlers/Handler.py"], "/examples/FunctionTest.py": ["/inputz/Devices.py"], "/examples/ControllerTest.py": ["/inputz/__init__.py", "/inputz/Devices.py"], "/inputz/invokations/Invokation.py": ["/inputz/handlers/Handler.py"], "/inputz/Devices.py": ["/inputz/exceptions/ControllerNotFound.py", "/inputz/Controller.py", "/inputz/controllers/__init__.py"], "/inputz/keys/Button.py": ["/inputz/Input.py"], "/inputz/controllers/__init__.py": ["/inputz/controllers/XboxController.py", "/inputz/controllers/XboxEliteController.py"], "/inputz/Controller.py": ["/inputz/handlers/Contentious.py", "/inputz/handlers/Single.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/invokations/__init__.py"], "/inputz/controllers/XboxEliteController.py": ["/inputz/controllers/__init__.py"], "/inputz/keys/Trigger.py": ["/inputz/Input.py"], "/inputz/invokations/__init__.py": ["/inputz/invokations/Invokation.py"]} |
57,264 | HCI902E18/inputz | refs/heads/master | /inputz/exceptions/ControllerNotFound.py | class ControllerNotFound(Exception):
pass
| {"/inputz/keys/Joystick.py": ["/inputz/Input.py"], "/examples/XboxController.py": ["/inputz/Devices.py"], "/inputz/__init__.py": ["/inputz/Controller.py", "/inputz/Devices.py", "/inputz/Input.py", "/inputz/invokations/Invokation.py", "/inputz/KillableThread.py", "/inputz/OS.py"], "/examples/EmbedClassTest.py": ["/inputz/Devices.py"], "/inputz/handlers/Contentious.py": ["/inputz/handlers/Handler.py"], "/inputz/controllers/XboxController.py": ["/inputz/Controller.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/OS.py", "/inputz/keys/__init__.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/examples/ClassTest.py": ["/inputz/Devices.py"], "/inputz/keys/__init__.py": ["/inputz/keys/Trigger.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/inputz/handlers/Single.py": ["/inputz/handlers/Handler.py"], "/examples/FunctionTest.py": ["/inputz/Devices.py"], "/examples/ControllerTest.py": ["/inputz/__init__.py", "/inputz/Devices.py"], "/inputz/invokations/Invokation.py": ["/inputz/handlers/Handler.py"], "/inputz/Devices.py": ["/inputz/exceptions/ControllerNotFound.py", "/inputz/Controller.py", "/inputz/controllers/__init__.py"], "/inputz/keys/Button.py": ["/inputz/Input.py"], "/inputz/controllers/__init__.py": ["/inputz/controllers/XboxController.py", "/inputz/controllers/XboxEliteController.py"], "/inputz/Controller.py": ["/inputz/handlers/Contentious.py", "/inputz/handlers/Single.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/invokations/__init__.py"], "/inputz/controllers/XboxEliteController.py": ["/inputz/controllers/__init__.py"], "/inputz/keys/Trigger.py": ["/inputz/Input.py"], "/inputz/invokations/__init__.py": ["/inputz/invokations/Invokation.py"]} |
57,265 | HCI902E18/inputz | refs/heads/master | /inputz/handlers/Handler.py | class Handler(object):
def should_emit(self, value):
return False
| {"/inputz/keys/Joystick.py": ["/inputz/Input.py"], "/examples/XboxController.py": ["/inputz/Devices.py"], "/inputz/__init__.py": ["/inputz/Controller.py", "/inputz/Devices.py", "/inputz/Input.py", "/inputz/invokations/Invokation.py", "/inputz/KillableThread.py", "/inputz/OS.py"], "/examples/EmbedClassTest.py": ["/inputz/Devices.py"], "/inputz/handlers/Contentious.py": ["/inputz/handlers/Handler.py"], "/inputz/controllers/XboxController.py": ["/inputz/Controller.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/OS.py", "/inputz/keys/__init__.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/examples/ClassTest.py": ["/inputz/Devices.py"], "/inputz/keys/__init__.py": ["/inputz/keys/Trigger.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/inputz/handlers/Single.py": ["/inputz/handlers/Handler.py"], "/examples/FunctionTest.py": ["/inputz/Devices.py"], "/examples/ControllerTest.py": ["/inputz/__init__.py", "/inputz/Devices.py"], "/inputz/invokations/Invokation.py": ["/inputz/handlers/Handler.py"], "/inputz/Devices.py": ["/inputz/exceptions/ControllerNotFound.py", "/inputz/Controller.py", "/inputz/controllers/__init__.py"], "/inputz/keys/Button.py": ["/inputz/Input.py"], "/inputz/controllers/__init__.py": ["/inputz/controllers/XboxController.py", "/inputz/controllers/XboxEliteController.py"], "/inputz/Controller.py": ["/inputz/handlers/Contentious.py", "/inputz/handlers/Single.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/invokations/__init__.py"], "/inputz/controllers/XboxEliteController.py": ["/inputz/controllers/__init__.py"], "/inputz/keys/Trigger.py": ["/inputz/Input.py"], "/inputz/invokations/__init__.py": ["/inputz/invokations/Invokation.py"]} |
57,266 | HCI902E18/inputz | refs/heads/master | /inputz/keys/Joystick.py | from copy import deepcopy
from inputs import InputEvent
from inputz.Input import Input
class Joystick(Input):
"""
Class mapping to X-Box Joystick
"""
def __init__(self, direction_x, direction_y, **kwargs):
super().__init__(kwargs.get('parse_func', None))
# Bumper might wobble, so this value is to filter those
self.offset_ = kwargs.get('offset', 15) / 100
# Joysticks move in two direction, these are mapped as a dictionary
self.__event = {
direction_x: 0,
direction_y: 0
}
# Default vector used checking for None values
self.default_vector = [0, 0]
# The interval the event will be within
self.interval = deepcopy(kwargs.get('interval', [-32768, 32767]))
# The current joystick vector
self.vector = deepcopy(self.default_vector)
# The last value the joystick reported to functions listen for it
self._last_report = deepcopy(self.default_vector)
def validate(self, event) -> bool:
"""
Validates if this event is for this joystick
:param event: Event from the controller
:return: bool
"""
if not isinstance(event, InputEvent): return False
for k, _ in self.__event.items():
if k == event.code:
return True
return False
def parse(self, event) -> None:
"""
Parse the event to get data for this joystick.
:param event: The event which data should be extracted from.
:return: None
"""
if not isinstance(event, InputEvent): return
_, code, value = super().parse(event)
if value < self.interval[0] or value > self.interval[1]:
self.log.error(f"{code}, {value}")
# Map the value to the direction of the joystick
self.__event[code] = value
# Recalculate the vector
self.calculate()
def calculate(self) -> None:
"""
Calculate the joystick vector
:return: None
"""
# Iterate through the directions of the joystick
for key, (_, value) in enumerate(self.__event.items()):
# Calculate the vector value
val_ = self.calc_vector_value(value)
# Handle wobble offset
if abs(val_) < self.offset_:
self.vector[key] = 0
else:
# Calculate value without offset
val_ = val_ + self.offset_ if val_ < 0 else val_ - self.offset_
# Maximum with offset
max_percent = 1 - self.offset_
self.vector[key] = val_ / max_percent
def calc_vector_value(self, value: int) -> float:
"""
Calculate the percentage vector in +/- directions
:param value: Value from the event
:return: percent direction
"""
if value == 0:
return 0
return self.percentage(value, self.interval[1 if value > 0 else 0])
@staticmethod
def percentage(value: int, _max: int) -> float:
"""
Calculate positive percentage from absolute values
:param value: The value of the numerator
:param _max: The value of the denominator
:return: float
"""
return value / abs(_max)
def value(self) -> list:
"""
Method that returns the value of the joystick.
Returns the value if the value changed since last report
Else report `None`
:return: None or list
"""
if self.vector == self._last_report == self.default_vector:
return None
if self.parse_func_ is None:
return self._set_last_report(self.vector_value)
return self.parse_func_(self._set_last_report(self.vector_value))
@property
def vector_value(self):
return deepcopy(self.vector)
| {"/inputz/keys/Joystick.py": ["/inputz/Input.py"], "/examples/XboxController.py": ["/inputz/Devices.py"], "/inputz/__init__.py": ["/inputz/Controller.py", "/inputz/Devices.py", "/inputz/Input.py", "/inputz/invokations/Invokation.py", "/inputz/KillableThread.py", "/inputz/OS.py"], "/examples/EmbedClassTest.py": ["/inputz/Devices.py"], "/inputz/handlers/Contentious.py": ["/inputz/handlers/Handler.py"], "/inputz/controllers/XboxController.py": ["/inputz/Controller.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/OS.py", "/inputz/keys/__init__.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/examples/ClassTest.py": ["/inputz/Devices.py"], "/inputz/keys/__init__.py": ["/inputz/keys/Trigger.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/inputz/handlers/Single.py": ["/inputz/handlers/Handler.py"], "/examples/FunctionTest.py": ["/inputz/Devices.py"], "/examples/ControllerTest.py": ["/inputz/__init__.py", "/inputz/Devices.py"], "/inputz/invokations/Invokation.py": ["/inputz/handlers/Handler.py"], "/inputz/Devices.py": ["/inputz/exceptions/ControllerNotFound.py", "/inputz/Controller.py", "/inputz/controllers/__init__.py"], "/inputz/keys/Button.py": ["/inputz/Input.py"], "/inputz/controllers/__init__.py": ["/inputz/controllers/XboxController.py", "/inputz/controllers/XboxEliteController.py"], "/inputz/Controller.py": ["/inputz/handlers/Contentious.py", "/inputz/handlers/Single.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/invokations/__init__.py"], "/inputz/controllers/XboxEliteController.py": ["/inputz/controllers/__init__.py"], "/inputz/keys/Trigger.py": ["/inputz/Input.py"], "/inputz/invokations/__init__.py": ["/inputz/invokations/Invokation.py"]} |
57,267 | HCI902E18/inputz | refs/heads/master | /examples/XboxController.py | from inputz.Devices import Devices
d = Devices()
device = d.get_device()
@device.listen('A', 'B')
def key_push(value):
print(f"key_push value 2: {value}")
@device.listen('A')
def push_a(value):
if value:
device.vibrate([1, 1])
print(f"push_a: {value}")
@device.listen('B')
def push_b(value):
if value:
device.vibrate([0, 0])
print(f"push_b: {value}")
@device.listen('RIGHT_TRIGGER')
def right_trigger(value):
print(f"right_trigger value: {value}")
@device.listen('LEFT_TRIGGER')
def left_trigger(value):
print(f"left_trigger value: {value}")
@device.listen('RIGHT_STICK')
def right_stick(value):
print(f"right_stick: {value}")
@device.listen('LEFT_STICK')
def left_stick(value):
print(f"left_stick: {value}")
if __name__ == "__main__":
device.run_unsecure()
device.start()
| {"/inputz/keys/Joystick.py": ["/inputz/Input.py"], "/examples/XboxController.py": ["/inputz/Devices.py"], "/inputz/__init__.py": ["/inputz/Controller.py", "/inputz/Devices.py", "/inputz/Input.py", "/inputz/invokations/Invokation.py", "/inputz/KillableThread.py", "/inputz/OS.py"], "/examples/EmbedClassTest.py": ["/inputz/Devices.py"], "/inputz/handlers/Contentious.py": ["/inputz/handlers/Handler.py"], "/inputz/controllers/XboxController.py": ["/inputz/Controller.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/OS.py", "/inputz/keys/__init__.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/examples/ClassTest.py": ["/inputz/Devices.py"], "/inputz/keys/__init__.py": ["/inputz/keys/Trigger.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/inputz/handlers/Single.py": ["/inputz/handlers/Handler.py"], "/examples/FunctionTest.py": ["/inputz/Devices.py"], "/examples/ControllerTest.py": ["/inputz/__init__.py", "/inputz/Devices.py"], "/inputz/invokations/Invokation.py": ["/inputz/handlers/Handler.py"], "/inputz/Devices.py": ["/inputz/exceptions/ControllerNotFound.py", "/inputz/Controller.py", "/inputz/controllers/__init__.py"], "/inputz/keys/Button.py": ["/inputz/Input.py"], "/inputz/controllers/__init__.py": ["/inputz/controllers/XboxController.py", "/inputz/controllers/XboxEliteController.py"], "/inputz/Controller.py": ["/inputz/handlers/Contentious.py", "/inputz/handlers/Single.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/invokations/__init__.py"], "/inputz/controllers/XboxEliteController.py": ["/inputz/controllers/__init__.py"], "/inputz/keys/Trigger.py": ["/inputz/Input.py"], "/inputz/invokations/__init__.py": ["/inputz/invokations/Invokation.py"]} |
57,268 | HCI902E18/inputz | refs/heads/master | /inputz/__init__.py | from .Controller import Controller
from .Devices import Devices
from .Input import Input
from inputz.invokations.Invokation import Invokation
from .KillableThread import KillableThread
from .OS import OS
| {"/inputz/keys/Joystick.py": ["/inputz/Input.py"], "/examples/XboxController.py": ["/inputz/Devices.py"], "/inputz/__init__.py": ["/inputz/Controller.py", "/inputz/Devices.py", "/inputz/Input.py", "/inputz/invokations/Invokation.py", "/inputz/KillableThread.py", "/inputz/OS.py"], "/examples/EmbedClassTest.py": ["/inputz/Devices.py"], "/inputz/handlers/Contentious.py": ["/inputz/handlers/Handler.py"], "/inputz/controllers/XboxController.py": ["/inputz/Controller.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/OS.py", "/inputz/keys/__init__.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/examples/ClassTest.py": ["/inputz/Devices.py"], "/inputz/keys/__init__.py": ["/inputz/keys/Trigger.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/inputz/handlers/Single.py": ["/inputz/handlers/Handler.py"], "/examples/FunctionTest.py": ["/inputz/Devices.py"], "/examples/ControllerTest.py": ["/inputz/__init__.py", "/inputz/Devices.py"], "/inputz/invokations/Invokation.py": ["/inputz/handlers/Handler.py"], "/inputz/Devices.py": ["/inputz/exceptions/ControllerNotFound.py", "/inputz/Controller.py", "/inputz/controllers/__init__.py"], "/inputz/keys/Button.py": ["/inputz/Input.py"], "/inputz/controllers/__init__.py": ["/inputz/controllers/XboxController.py", "/inputz/controllers/XboxEliteController.py"], "/inputz/Controller.py": ["/inputz/handlers/Contentious.py", "/inputz/handlers/Single.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/invokations/__init__.py"], "/inputz/controllers/XboxEliteController.py": ["/inputz/controllers/__init__.py"], "/inputz/keys/Trigger.py": ["/inputz/Input.py"], "/inputz/invokations/__init__.py": ["/inputz/invokations/Invokation.py"]} |
57,269 | HCI902E18/inputz | refs/heads/master | /examples/EmbedClassTest.py | from inputz.Devices import Devices
class TestClass(object):
def __init__(self):
self.device = Devices().get_device()
self.device.method_listener(self.test_method, 'A')
def test_method(self, args):
print('test_method', args)
return
def start(self):
self.device.start()
if __name__ == "__main__":
t = TestClass()
t.start()
| {"/inputz/keys/Joystick.py": ["/inputz/Input.py"], "/examples/XboxController.py": ["/inputz/Devices.py"], "/inputz/__init__.py": ["/inputz/Controller.py", "/inputz/Devices.py", "/inputz/Input.py", "/inputz/invokations/Invokation.py", "/inputz/KillableThread.py", "/inputz/OS.py"], "/examples/EmbedClassTest.py": ["/inputz/Devices.py"], "/inputz/handlers/Contentious.py": ["/inputz/handlers/Handler.py"], "/inputz/controllers/XboxController.py": ["/inputz/Controller.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/OS.py", "/inputz/keys/__init__.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/examples/ClassTest.py": ["/inputz/Devices.py"], "/inputz/keys/__init__.py": ["/inputz/keys/Trigger.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/inputz/handlers/Single.py": ["/inputz/handlers/Handler.py"], "/examples/FunctionTest.py": ["/inputz/Devices.py"], "/examples/ControllerTest.py": ["/inputz/__init__.py", "/inputz/Devices.py"], "/inputz/invokations/Invokation.py": ["/inputz/handlers/Handler.py"], "/inputz/Devices.py": ["/inputz/exceptions/ControllerNotFound.py", "/inputz/Controller.py", "/inputz/controllers/__init__.py"], "/inputz/keys/Button.py": ["/inputz/Input.py"], "/inputz/controllers/__init__.py": ["/inputz/controllers/XboxController.py", "/inputz/controllers/XboxEliteController.py"], "/inputz/Controller.py": ["/inputz/handlers/Contentious.py", "/inputz/handlers/Single.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/invokations/__init__.py"], "/inputz/controllers/XboxEliteController.py": ["/inputz/controllers/__init__.py"], "/inputz/keys/Trigger.py": ["/inputz/Input.py"], "/inputz/invokations/__init__.py": ["/inputz/invokations/Invokation.py"]} |
57,270 | HCI902E18/inputz | refs/heads/master | /inputz/handlers/Contentious.py | from .Handler import Handler
class Contentious(Handler):
def should_emit(self, value):
return True
| {"/inputz/keys/Joystick.py": ["/inputz/Input.py"], "/examples/XboxController.py": ["/inputz/Devices.py"], "/inputz/__init__.py": ["/inputz/Controller.py", "/inputz/Devices.py", "/inputz/Input.py", "/inputz/invokations/Invokation.py", "/inputz/KillableThread.py", "/inputz/OS.py"], "/examples/EmbedClassTest.py": ["/inputz/Devices.py"], "/inputz/handlers/Contentious.py": ["/inputz/handlers/Handler.py"], "/inputz/controllers/XboxController.py": ["/inputz/Controller.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/OS.py", "/inputz/keys/__init__.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/examples/ClassTest.py": ["/inputz/Devices.py"], "/inputz/keys/__init__.py": ["/inputz/keys/Trigger.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/inputz/handlers/Single.py": ["/inputz/handlers/Handler.py"], "/examples/FunctionTest.py": ["/inputz/Devices.py"], "/examples/ControllerTest.py": ["/inputz/__init__.py", "/inputz/Devices.py"], "/inputz/invokations/Invokation.py": ["/inputz/handlers/Handler.py"], "/inputz/Devices.py": ["/inputz/exceptions/ControllerNotFound.py", "/inputz/Controller.py", "/inputz/controllers/__init__.py"], "/inputz/keys/Button.py": ["/inputz/Input.py"], "/inputz/controllers/__init__.py": ["/inputz/controllers/XboxController.py", "/inputz/controllers/XboxEliteController.py"], "/inputz/Controller.py": ["/inputz/handlers/Contentious.py", "/inputz/handlers/Single.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/invokations/__init__.py"], "/inputz/controllers/XboxEliteController.py": ["/inputz/controllers/__init__.py"], "/inputz/keys/Trigger.py": ["/inputz/Input.py"], "/inputz/invokations/__init__.py": ["/inputz/invokations/Invokation.py"]} |
57,271 | HCI902E18/inputz | refs/heads/master | /inputz/controllers/XboxController.py | import enum
from copy import deepcopy
from inputs import UnpluggedError, InputEvent
from inputz.Controller import Controller
from inputz.Input import Input
from inputz.KillableThread import KillableThread
from inputz.OS import OS
from inputz.keys import Trigger
from inputz.keys.Button import Button
from inputz.keys.Joystick import Joystick
class XboxController(Controller):
"""
Xbox controller mappings
"""
@staticmethod
def validate(name: str) -> bool:
"""
Used to validate if the name of the controller matches this controller
:param name: The name of the input controller
:return: bool, if the controller matches
"""
return name == 'Microsoft X-Box 360 pad'
@property
def name(self) -> str:
"""
Gets the name of the connected device
:return: String, name of device
"""
return self.device.name
def __init__(self, device):
# Needs for logger to start
super().__init__()
# Which device this controller listen on
self.device = device
# Maps all the buttons on the controller
self.A = Button('BTN_SOUTH')
self.B = Button('BTN_EAST')
self.X = Button(self.reverse_binding(win='BTN_WEST', linux='BTN_NORTH'))
self.Y = Button(self.reverse_binding(win='BTN_NORTH', linux='BTN_WEST'))
self.START = Button(self.reverse_binding(win='BTN_SELECT', linux='BTN_START'))
self.SELECT = Button(self.reverse_binding(win='BTN_START', linux='BTN_SELECT'))
self.RIGHT_BUMPER = Button('BTN_TR')
self.LEFT_BUMPER = Button('BTN_TL')
self.ARROWS = Joystick('ABS_HAT0X', 'ABS_HAT0Y', interval=[-1, 1])
self.LEFT_STICK = Joystick('ABS_X', 'ABS_Y', parse_func=self.joystick_linux_converter)
self.LEFT_STICK_BUTTON = Button('BTN_THUMBL')
self.RIGHT_STICK = Joystick('ABS_RX', 'ABS_RY', parse_func=self.joystick_linux_converter)
self.RIGHT_STICK_BUTTON = Button('BTN_THUMBR')
self.RIGHT_TRIGGER = Trigger('ABS_RZ', interval=self.os_interval())
self.LEFT_TRIGGER = Trigger('ABS_Z', interval=self.os_interval())
# This controller needs a thread which listens for controller inputs
self.add_thread(KillableThread(name="ControllerThread", target=self.__event_listener, args=()))
# Vibration vector
self.vibrate_state = [0, 0]
class Side(enum.Enum):
left = 0
right = 1
def os_interval(self):
if self.os == self.OS.linux:
return [0, 1023]
return [0, 255]
def joystick_linux_converter(self, value):
if self.os == self.OS.linux:
value[1] = -value[1]
return value
def reverse_binding(self, **kwargs):
if self.os == self.OS.win:
return kwargs.get('win')
elif self.os == self.OS.linux:
return kwargs.get('linux')
raise Exception('Mac is not yet supported')
def read(self) -> list:
"""
Method used for reading the input from the controller
:return: list, the events from inputs on controller
"""
try:
return self.device.read()
except (UnpluggedError, OSError):
# In case of disconnection, ABORT EVERYTHING
self.abort()
# If controller looses connection, this will catch it.
self.log.error("The controller has been unplugged, application terminating")
exit(1)
def __event_listener(self) -> None:
"""
Thread method which handles all events from controller
:return: None
"""
while not self.kill_state():
for event in self.read():
self.log.debug(event.code)
self.parse(event)
def parse(self, event: InputEvent) -> None:
"""
Parser for controller events, tests whether the event belongs to a specific input
:param event: the event from the controller
:return: None
"""
# We iterate through all properties on the class it self.
for _, cls_prop in self.__dict__.items():
# Checks if the property is instance of input
if isinstance(cls_prop, Input):
# Checks if the event belongs to this property
if cls_prop.validate(event):
# Parse the event according to the input
cls_prop.parse(event)
def vibrate(self, value: list) -> None:
"""
Method used for vibrating the entire controller
:param value: list of vibration level, scale is 0..1
:return: None
"""
if not isinstance(value, list) or len(value) != 2:
self.log.warn("Invalid vibration format")
return
self.set_vibrate(value)
def vibrate_left(self, value: int) -> None:
"""
Method for vibrate only the left site of the controller
:param value: Integer value, 0..1
:return: None
"""
self.set_vibrate(value, self.Side.left)
def vibrate_right(self, value: int) -> None:
"""
Method for vibrate only the right site of the controller
:param value: Integer value, 0..1
:return: None
"""
self.set_vibrate(value, self.Side.right)
def set_vibrate(self, value, side=None) -> None:
"""
Sets the vibration value in vibration state
:param value: The value for the vibration state
:param side: The side of the controller
:return: None
"""
if isinstance(side, self.Side):
self.vibrate_state[side.value] = value
elif isinstance(value, list):
# We need deep copy, not the reference
self.vibrate_state = deepcopy(value)
# Send the update to the controller
self.update_vibrate()
def update_vibrate(self) -> None:
"""
Send the vibration state to the controller
:return: None
"""
if OS.WIN:
self.device._start_vibration_win(*self.vibrate_state)
elif OS.NIX:
# untested!
self.device._set_vibration_nix(*self.vibrate_state, 1000)
| {"/inputz/keys/Joystick.py": ["/inputz/Input.py"], "/examples/XboxController.py": ["/inputz/Devices.py"], "/inputz/__init__.py": ["/inputz/Controller.py", "/inputz/Devices.py", "/inputz/Input.py", "/inputz/invokations/Invokation.py", "/inputz/KillableThread.py", "/inputz/OS.py"], "/examples/EmbedClassTest.py": ["/inputz/Devices.py"], "/inputz/handlers/Contentious.py": ["/inputz/handlers/Handler.py"], "/inputz/controllers/XboxController.py": ["/inputz/Controller.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/OS.py", "/inputz/keys/__init__.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/examples/ClassTest.py": ["/inputz/Devices.py"], "/inputz/keys/__init__.py": ["/inputz/keys/Trigger.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/inputz/handlers/Single.py": ["/inputz/handlers/Handler.py"], "/examples/FunctionTest.py": ["/inputz/Devices.py"], "/examples/ControllerTest.py": ["/inputz/__init__.py", "/inputz/Devices.py"], "/inputz/invokations/Invokation.py": ["/inputz/handlers/Handler.py"], "/inputz/Devices.py": ["/inputz/exceptions/ControllerNotFound.py", "/inputz/Controller.py", "/inputz/controllers/__init__.py"], "/inputz/keys/Button.py": ["/inputz/Input.py"], "/inputz/controllers/__init__.py": ["/inputz/controllers/XboxController.py", "/inputz/controllers/XboxEliteController.py"], "/inputz/Controller.py": ["/inputz/handlers/Contentious.py", "/inputz/handlers/Single.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/invokations/__init__.py"], "/inputz/controllers/XboxEliteController.py": ["/inputz/controllers/__init__.py"], "/inputz/keys/Trigger.py": ["/inputz/Input.py"], "/inputz/invokations/__init__.py": ["/inputz/invokations/Invokation.py"]} |
57,272 | HCI902E18/inputz | refs/heads/master | /examples/ClassTest.py | from inputz.Devices import Devices
d = Devices()
device = d.get_device()
@device.listen('A', handler=device.Handler.single)
def test_func(args):
print('test_func', args)
return
@device.abort_function
def abort():
print("TEST FUNCTION ABORTING")
return
class TestClass(object):
def __init__(self):
device.method_listener(self.test_method, 'A', device.Handler.single)
device.abort_method(self.abort)
def test_method(self, args):
print('test_method', args)
return
def abort(self):
print("TEST CLASS ABORTING")
return
if __name__ == "__main__":
t = TestClass()
device.start()
| {"/inputz/keys/Joystick.py": ["/inputz/Input.py"], "/examples/XboxController.py": ["/inputz/Devices.py"], "/inputz/__init__.py": ["/inputz/Controller.py", "/inputz/Devices.py", "/inputz/Input.py", "/inputz/invokations/Invokation.py", "/inputz/KillableThread.py", "/inputz/OS.py"], "/examples/EmbedClassTest.py": ["/inputz/Devices.py"], "/inputz/handlers/Contentious.py": ["/inputz/handlers/Handler.py"], "/inputz/controllers/XboxController.py": ["/inputz/Controller.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/OS.py", "/inputz/keys/__init__.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/examples/ClassTest.py": ["/inputz/Devices.py"], "/inputz/keys/__init__.py": ["/inputz/keys/Trigger.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/inputz/handlers/Single.py": ["/inputz/handlers/Handler.py"], "/examples/FunctionTest.py": ["/inputz/Devices.py"], "/examples/ControllerTest.py": ["/inputz/__init__.py", "/inputz/Devices.py"], "/inputz/invokations/Invokation.py": ["/inputz/handlers/Handler.py"], "/inputz/Devices.py": ["/inputz/exceptions/ControllerNotFound.py", "/inputz/Controller.py", "/inputz/controllers/__init__.py"], "/inputz/keys/Button.py": ["/inputz/Input.py"], "/inputz/controllers/__init__.py": ["/inputz/controllers/XboxController.py", "/inputz/controllers/XboxEliteController.py"], "/inputz/Controller.py": ["/inputz/handlers/Contentious.py", "/inputz/handlers/Single.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/invokations/__init__.py"], "/inputz/controllers/XboxEliteController.py": ["/inputz/controllers/__init__.py"], "/inputz/keys/Trigger.py": ["/inputz/Input.py"], "/inputz/invokations/__init__.py": ["/inputz/invokations/Invokation.py"]} |
57,273 | HCI902E18/inputz | refs/heads/master | /inputz/keys/__init__.py | from .Trigger import Trigger
from .Button import Button
from .Joystick import Joystick
| {"/inputz/keys/Joystick.py": ["/inputz/Input.py"], "/examples/XboxController.py": ["/inputz/Devices.py"], "/inputz/__init__.py": ["/inputz/Controller.py", "/inputz/Devices.py", "/inputz/Input.py", "/inputz/invokations/Invokation.py", "/inputz/KillableThread.py", "/inputz/OS.py"], "/examples/EmbedClassTest.py": ["/inputz/Devices.py"], "/inputz/handlers/Contentious.py": ["/inputz/handlers/Handler.py"], "/inputz/controllers/XboxController.py": ["/inputz/Controller.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/OS.py", "/inputz/keys/__init__.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/examples/ClassTest.py": ["/inputz/Devices.py"], "/inputz/keys/__init__.py": ["/inputz/keys/Trigger.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/inputz/handlers/Single.py": ["/inputz/handlers/Handler.py"], "/examples/FunctionTest.py": ["/inputz/Devices.py"], "/examples/ControllerTest.py": ["/inputz/__init__.py", "/inputz/Devices.py"], "/inputz/invokations/Invokation.py": ["/inputz/handlers/Handler.py"], "/inputz/Devices.py": ["/inputz/exceptions/ControllerNotFound.py", "/inputz/Controller.py", "/inputz/controllers/__init__.py"], "/inputz/keys/Button.py": ["/inputz/Input.py"], "/inputz/controllers/__init__.py": ["/inputz/controllers/XboxController.py", "/inputz/controllers/XboxEliteController.py"], "/inputz/Controller.py": ["/inputz/handlers/Contentious.py", "/inputz/handlers/Single.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/invokations/__init__.py"], "/inputz/controllers/XboxEliteController.py": ["/inputz/controllers/__init__.py"], "/inputz/keys/Trigger.py": ["/inputz/Input.py"], "/inputz/invokations/__init__.py": ["/inputz/invokations/Invokation.py"]} |
57,274 | HCI902E18/inputz | refs/heads/master | /inputz/handlers/Single.py | from .Handler import Handler
class Single(Handler):
def __init__(self):
self.last_value = False
return
def should_emit(self, value):
if self.last_value == value:
return False
self.last_value = value
return True
| {"/inputz/keys/Joystick.py": ["/inputz/Input.py"], "/examples/XboxController.py": ["/inputz/Devices.py"], "/inputz/__init__.py": ["/inputz/Controller.py", "/inputz/Devices.py", "/inputz/Input.py", "/inputz/invokations/Invokation.py", "/inputz/KillableThread.py", "/inputz/OS.py"], "/examples/EmbedClassTest.py": ["/inputz/Devices.py"], "/inputz/handlers/Contentious.py": ["/inputz/handlers/Handler.py"], "/inputz/controllers/XboxController.py": ["/inputz/Controller.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/OS.py", "/inputz/keys/__init__.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/examples/ClassTest.py": ["/inputz/Devices.py"], "/inputz/keys/__init__.py": ["/inputz/keys/Trigger.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/inputz/handlers/Single.py": ["/inputz/handlers/Handler.py"], "/examples/FunctionTest.py": ["/inputz/Devices.py"], "/examples/ControllerTest.py": ["/inputz/__init__.py", "/inputz/Devices.py"], "/inputz/invokations/Invokation.py": ["/inputz/handlers/Handler.py"], "/inputz/Devices.py": ["/inputz/exceptions/ControllerNotFound.py", "/inputz/Controller.py", "/inputz/controllers/__init__.py"], "/inputz/keys/Button.py": ["/inputz/Input.py"], "/inputz/controllers/__init__.py": ["/inputz/controllers/XboxController.py", "/inputz/controllers/XboxEliteController.py"], "/inputz/Controller.py": ["/inputz/handlers/Contentious.py", "/inputz/handlers/Single.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/invokations/__init__.py"], "/inputz/controllers/XboxEliteController.py": ["/inputz/controllers/__init__.py"], "/inputz/keys/Trigger.py": ["/inputz/Input.py"], "/inputz/invokations/__init__.py": ["/inputz/invokations/Invokation.py"]} |
57,275 | HCI902E18/inputz | refs/heads/master | /examples/FunctionTest.py | from inputz.Devices import Devices
d = Devices()
device = d.get_device()
@device.listen('A')
def test_func(args):
print('test_func', args)
return
if __name__ == "__main__":
test_func("1")
test_func("2")
test_func("3")
test_func("4")
test_func("5")
test_func("6")
device.start()
| {"/inputz/keys/Joystick.py": ["/inputz/Input.py"], "/examples/XboxController.py": ["/inputz/Devices.py"], "/inputz/__init__.py": ["/inputz/Controller.py", "/inputz/Devices.py", "/inputz/Input.py", "/inputz/invokations/Invokation.py", "/inputz/KillableThread.py", "/inputz/OS.py"], "/examples/EmbedClassTest.py": ["/inputz/Devices.py"], "/inputz/handlers/Contentious.py": ["/inputz/handlers/Handler.py"], "/inputz/controllers/XboxController.py": ["/inputz/Controller.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/OS.py", "/inputz/keys/__init__.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/examples/ClassTest.py": ["/inputz/Devices.py"], "/inputz/keys/__init__.py": ["/inputz/keys/Trigger.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/inputz/handlers/Single.py": ["/inputz/handlers/Handler.py"], "/examples/FunctionTest.py": ["/inputz/Devices.py"], "/examples/ControllerTest.py": ["/inputz/__init__.py", "/inputz/Devices.py"], "/inputz/invokations/Invokation.py": ["/inputz/handlers/Handler.py"], "/inputz/Devices.py": ["/inputz/exceptions/ControllerNotFound.py", "/inputz/Controller.py", "/inputz/controllers/__init__.py"], "/inputz/keys/Button.py": ["/inputz/Input.py"], "/inputz/controllers/__init__.py": ["/inputz/controllers/XboxController.py", "/inputz/controllers/XboxEliteController.py"], "/inputz/Controller.py": ["/inputz/handlers/Contentious.py", "/inputz/handlers/Single.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/invokations/__init__.py"], "/inputz/controllers/XboxEliteController.py": ["/inputz/controllers/__init__.py"], "/inputz/keys/Trigger.py": ["/inputz/Input.py"], "/inputz/invokations/__init__.py": ["/inputz/invokations/Invokation.py"]} |
57,276 | HCI902E18/inputz | refs/heads/master | /examples/ControllerTest.py | from inputz import Input
from inputz.Devices import Devices
class ControllerTest(object):
def __init__(self):
d = Devices()
self.device = d.get_device()
self.keys = [k for k, v in self.device.__dict__.items() if isinstance(v, Input)]
self.pop_next()
self.device.run_unsecure()
self.device.start()
def pop_next(self):
if len(self.keys) > 0:
key = self.keys.pop()
self.device.clear_invocations()
print(f"Press {key}")
self.device.method_listener(self.key, key)
else:
print("ALL KEYS SUCCESSFULLY FOUND!")
self.device.terminate()
exit(1)
def key(self, val):
print('PRESSED')
self.pop_next()
if __name__ == "__main__":
ct = ControllerTest()
| {"/inputz/keys/Joystick.py": ["/inputz/Input.py"], "/examples/XboxController.py": ["/inputz/Devices.py"], "/inputz/__init__.py": ["/inputz/Controller.py", "/inputz/Devices.py", "/inputz/Input.py", "/inputz/invokations/Invokation.py", "/inputz/KillableThread.py", "/inputz/OS.py"], "/examples/EmbedClassTest.py": ["/inputz/Devices.py"], "/inputz/handlers/Contentious.py": ["/inputz/handlers/Handler.py"], "/inputz/controllers/XboxController.py": ["/inputz/Controller.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/OS.py", "/inputz/keys/__init__.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/examples/ClassTest.py": ["/inputz/Devices.py"], "/inputz/keys/__init__.py": ["/inputz/keys/Trigger.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/inputz/handlers/Single.py": ["/inputz/handlers/Handler.py"], "/examples/FunctionTest.py": ["/inputz/Devices.py"], "/examples/ControllerTest.py": ["/inputz/__init__.py", "/inputz/Devices.py"], "/inputz/invokations/Invokation.py": ["/inputz/handlers/Handler.py"], "/inputz/Devices.py": ["/inputz/exceptions/ControllerNotFound.py", "/inputz/Controller.py", "/inputz/controllers/__init__.py"], "/inputz/keys/Button.py": ["/inputz/Input.py"], "/inputz/controllers/__init__.py": ["/inputz/controllers/XboxController.py", "/inputz/controllers/XboxEliteController.py"], "/inputz/Controller.py": ["/inputz/handlers/Contentious.py", "/inputz/handlers/Single.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/invokations/__init__.py"], "/inputz/controllers/XboxEliteController.py": ["/inputz/controllers/__init__.py"], "/inputz/keys/Trigger.py": ["/inputz/Input.py"], "/inputz/invokations/__init__.py": ["/inputz/invokations/Invokation.py"]} |
57,277 | HCI902E18/inputz | refs/heads/master | /inputz/invokations/Invokation.py | from inputz.handlers.Handler import Handler
from inputz.logging import Logger
class Invokation(Logger):
"""
Class used for triggering functions through bindings
"""
def __init__(self, func: "function", key: str, handler: Handler):
super().__init__()
self.func = func
self.key = key
self.handler = handler
def is_(self, key: str) -> bool:
"""
Checks if the key should trigger the function related to this invokation
:param key: The currently pressed key as string
:return: boolean, true if key is this key
"""
return self.key.upper() == key.upper()
def transmit(self, value: object) -> None:
"""
Method used for sending data to functions
:param value: The value which should be passed on to the function
:param cls: The class which the method may belong to
:return: None
"""
if callable(self.func):
if self.handler.should_emit(value):
self.func(value)
else:
raise Exception('Function is not callable')
| {"/inputz/keys/Joystick.py": ["/inputz/Input.py"], "/examples/XboxController.py": ["/inputz/Devices.py"], "/inputz/__init__.py": ["/inputz/Controller.py", "/inputz/Devices.py", "/inputz/Input.py", "/inputz/invokations/Invokation.py", "/inputz/KillableThread.py", "/inputz/OS.py"], "/examples/EmbedClassTest.py": ["/inputz/Devices.py"], "/inputz/handlers/Contentious.py": ["/inputz/handlers/Handler.py"], "/inputz/controllers/XboxController.py": ["/inputz/Controller.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/OS.py", "/inputz/keys/__init__.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/examples/ClassTest.py": ["/inputz/Devices.py"], "/inputz/keys/__init__.py": ["/inputz/keys/Trigger.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/inputz/handlers/Single.py": ["/inputz/handlers/Handler.py"], "/examples/FunctionTest.py": ["/inputz/Devices.py"], "/examples/ControllerTest.py": ["/inputz/__init__.py", "/inputz/Devices.py"], "/inputz/invokations/Invokation.py": ["/inputz/handlers/Handler.py"], "/inputz/Devices.py": ["/inputz/exceptions/ControllerNotFound.py", "/inputz/Controller.py", "/inputz/controllers/__init__.py"], "/inputz/keys/Button.py": ["/inputz/Input.py"], "/inputz/controllers/__init__.py": ["/inputz/controllers/XboxController.py", "/inputz/controllers/XboxEliteController.py"], "/inputz/Controller.py": ["/inputz/handlers/Contentious.py", "/inputz/handlers/Single.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/invokations/__init__.py"], "/inputz/controllers/XboxEliteController.py": ["/inputz/controllers/__init__.py"], "/inputz/keys/Trigger.py": ["/inputz/Input.py"], "/inputz/invokations/__init__.py": ["/inputz/invokations/Invokation.py"]} |
57,278 | HCI902E18/inputz | refs/heads/master | /inputz/Devices.py | from inputs import devices
from inputz.exceptions.ControllerNotFound import ControllerNotFound
from .Controller import Controller
from .controllers import XboxController, XboxEliteController
from .logging import Logger
class Devices(Logger):
"""
Loads the devices which can be recognized by the libaries, and maps to local controller classes.
"""
def __init__(self):
super().__init__()
# List of all controllers which can be mapped
self.controllers = [
# Xbox controller
XboxController,
# Xbox mater race
XboxEliteController,
]
def get_device(self):
"""
Returns the device which should be used.
If no device is connected this WILL kill the program.
If multiple controllers connected, the users will be promoted to choose controller.
:return: instance of the controller which is going to be used.
"""
# List of all found controllers
_controllers = []
# Iterate through all controllers found by `inputs`
for device in devices:
self.log.debug(f"Found: {device.name}")
for controller in self.controllers:
# Checks if the device found by `inputs` is available as controller instance
if controller.validate(device.name):
_controllers.append(controller(device))
# Checks if any controllers were found
if len(_controllers) == 0:
self.log.error("No supported controller found.")
raise ControllerNotFound()
# Handle the case where multiple controllers were found
elif len(_controllers) > 1:
return self.choose_device(_controllers)
# If only one controller found, return this
return _controllers[0]
def choose_device(self, controllers: list) -> Controller:
"""
Allows for the user to choose between a list of controllers
:param controllers: List of class instances of controllers
:return: The controller which is going to be used
"""
self.log.info("More then 1 device has been found, please choose controller to use.")
for idx, device in enumerate(controllers):
self.log.info(f"{idx}) {device.name}")
while True:
# Get's the users input
i = self.int_input("Enter device id:")
# Checks if the chosen controller is within the list
if 0 <= i < len(controllers):
# Returns the chosen controller
return controllers[i]
else:
self.log.info("Number not within range.")
def int_input(self, text: str) -> int:
"""
Assures that the user input is an integer
:param text: The text which is displayed next to the user input.
:return: The number the user has chosen
"""
i = input(text)
try:
return int(i)
except ValueError:
self.log.info("Value is not an recognized integer")
# Recursive, until the user has chosen an integer
return self.int_input(text)
| {"/inputz/keys/Joystick.py": ["/inputz/Input.py"], "/examples/XboxController.py": ["/inputz/Devices.py"], "/inputz/__init__.py": ["/inputz/Controller.py", "/inputz/Devices.py", "/inputz/Input.py", "/inputz/invokations/Invokation.py", "/inputz/KillableThread.py", "/inputz/OS.py"], "/examples/EmbedClassTest.py": ["/inputz/Devices.py"], "/inputz/handlers/Contentious.py": ["/inputz/handlers/Handler.py"], "/inputz/controllers/XboxController.py": ["/inputz/Controller.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/OS.py", "/inputz/keys/__init__.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/examples/ClassTest.py": ["/inputz/Devices.py"], "/inputz/keys/__init__.py": ["/inputz/keys/Trigger.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/inputz/handlers/Single.py": ["/inputz/handlers/Handler.py"], "/examples/FunctionTest.py": ["/inputz/Devices.py"], "/examples/ControllerTest.py": ["/inputz/__init__.py", "/inputz/Devices.py"], "/inputz/invokations/Invokation.py": ["/inputz/handlers/Handler.py"], "/inputz/Devices.py": ["/inputz/exceptions/ControllerNotFound.py", "/inputz/Controller.py", "/inputz/controllers/__init__.py"], "/inputz/keys/Button.py": ["/inputz/Input.py"], "/inputz/controllers/__init__.py": ["/inputz/controllers/XboxController.py", "/inputz/controllers/XboxEliteController.py"], "/inputz/Controller.py": ["/inputz/handlers/Contentious.py", "/inputz/handlers/Single.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/invokations/__init__.py"], "/inputz/controllers/XboxEliteController.py": ["/inputz/controllers/__init__.py"], "/inputz/keys/Trigger.py": ["/inputz/Input.py"], "/inputz/invokations/__init__.py": ["/inputz/invokations/Invokation.py"]} |
57,279 | HCI902E18/inputz | refs/heads/master | /inputz/keys/Button.py | from inputs import InputEvent
from inputz.Input import Input
class Button(Input):
"""
Class mapping to X-Box Buttons
"""
def __init__(self, event, **kwargs):
super().__init__(kwargs.get('parse_func', None))
# This is the event the button will listen for
self.__event = event
# The current state of the button
self.__state = False
# The last value the button reported to functions listen for it
self._last_report = False
def validate(self, event: InputEvent) -> bool:
"""
Validates if this event is for this button
:param event: Event from the controller
:return: bool
"""
if not isinstance(event, InputEvent): return False
return event.code == self.__event
def parse(self, event) -> None:
"""
Parse the event to get data for this button.
:param event: The event which data should be extracted from.
:return: None
"""
if not isinstance(event, InputEvent): return
_, _, state_ = super().parse(event)
self.__state = bool(state_)
def value(self) -> bool:
"""
Method that returns the value of the button.
Returns the value if the value changed since last report
Else report `None`
:return: None or bool
"""
if self.__state == self._last_report and not self.__state:
return None
if self.parse_func_ is None:
return self._set_last_report(self.__state)
return self.parse_func_(self._set_last_report(self.__state))
| {"/inputz/keys/Joystick.py": ["/inputz/Input.py"], "/examples/XboxController.py": ["/inputz/Devices.py"], "/inputz/__init__.py": ["/inputz/Controller.py", "/inputz/Devices.py", "/inputz/Input.py", "/inputz/invokations/Invokation.py", "/inputz/KillableThread.py", "/inputz/OS.py"], "/examples/EmbedClassTest.py": ["/inputz/Devices.py"], "/inputz/handlers/Contentious.py": ["/inputz/handlers/Handler.py"], "/inputz/controllers/XboxController.py": ["/inputz/Controller.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/OS.py", "/inputz/keys/__init__.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/examples/ClassTest.py": ["/inputz/Devices.py"], "/inputz/keys/__init__.py": ["/inputz/keys/Trigger.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/inputz/handlers/Single.py": ["/inputz/handlers/Handler.py"], "/examples/FunctionTest.py": ["/inputz/Devices.py"], "/examples/ControllerTest.py": ["/inputz/__init__.py", "/inputz/Devices.py"], "/inputz/invokations/Invokation.py": ["/inputz/handlers/Handler.py"], "/inputz/Devices.py": ["/inputz/exceptions/ControllerNotFound.py", "/inputz/Controller.py", "/inputz/controllers/__init__.py"], "/inputz/keys/Button.py": ["/inputz/Input.py"], "/inputz/controllers/__init__.py": ["/inputz/controllers/XboxController.py", "/inputz/controllers/XboxEliteController.py"], "/inputz/Controller.py": ["/inputz/handlers/Contentious.py", "/inputz/handlers/Single.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/invokations/__init__.py"], "/inputz/controllers/XboxEliteController.py": ["/inputz/controllers/__init__.py"], "/inputz/keys/Trigger.py": ["/inputz/Input.py"], "/inputz/invokations/__init__.py": ["/inputz/invokations/Invokation.py"]} |
57,280 | HCI902E18/inputz | refs/heads/master | /inputz/KillableThread.py | import threading
class KillableThread(threading.Thread):
def kill(self, consequences: bool = False) -> None:
"""
This method will overwrite all thread locks and just kill the thread
This code is NOT safety critical, but will kill thread waiting for iterator
:param consequences: Bool to ensure that the user
understands the consequences of this method
:return: None
"""
if not consequences:
raise RuntimeError("YOU NEED TO UNDERSTAND THE CONSEQUENCES OF THIS METHOD")
lock = self._tstate_lock
# THIS THREADING SHOULD NOT HOLD CRITICAL CODE
if lock is not None and lock.locked():
lock.release()
self.join()
| {"/inputz/keys/Joystick.py": ["/inputz/Input.py"], "/examples/XboxController.py": ["/inputz/Devices.py"], "/inputz/__init__.py": ["/inputz/Controller.py", "/inputz/Devices.py", "/inputz/Input.py", "/inputz/invokations/Invokation.py", "/inputz/KillableThread.py", "/inputz/OS.py"], "/examples/EmbedClassTest.py": ["/inputz/Devices.py"], "/inputz/handlers/Contentious.py": ["/inputz/handlers/Handler.py"], "/inputz/controllers/XboxController.py": ["/inputz/Controller.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/OS.py", "/inputz/keys/__init__.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/examples/ClassTest.py": ["/inputz/Devices.py"], "/inputz/keys/__init__.py": ["/inputz/keys/Trigger.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/inputz/handlers/Single.py": ["/inputz/handlers/Handler.py"], "/examples/FunctionTest.py": ["/inputz/Devices.py"], "/examples/ControllerTest.py": ["/inputz/__init__.py", "/inputz/Devices.py"], "/inputz/invokations/Invokation.py": ["/inputz/handlers/Handler.py"], "/inputz/Devices.py": ["/inputz/exceptions/ControllerNotFound.py", "/inputz/Controller.py", "/inputz/controllers/__init__.py"], "/inputz/keys/Button.py": ["/inputz/Input.py"], "/inputz/controllers/__init__.py": ["/inputz/controllers/XboxController.py", "/inputz/controllers/XboxEliteController.py"], "/inputz/Controller.py": ["/inputz/handlers/Contentious.py", "/inputz/handlers/Single.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/invokations/__init__.py"], "/inputz/controllers/XboxEliteController.py": ["/inputz/controllers/__init__.py"], "/inputz/keys/Trigger.py": ["/inputz/Input.py"], "/inputz/invokations/__init__.py": ["/inputz/invokations/Invokation.py"]} |
57,281 | HCI902E18/inputz | refs/heads/master | /inputz/controllers/__init__.py | from .XboxController import XboxController
from .XboxEliteController import XboxEliteController
| {"/inputz/keys/Joystick.py": ["/inputz/Input.py"], "/examples/XboxController.py": ["/inputz/Devices.py"], "/inputz/__init__.py": ["/inputz/Controller.py", "/inputz/Devices.py", "/inputz/Input.py", "/inputz/invokations/Invokation.py", "/inputz/KillableThread.py", "/inputz/OS.py"], "/examples/EmbedClassTest.py": ["/inputz/Devices.py"], "/inputz/handlers/Contentious.py": ["/inputz/handlers/Handler.py"], "/inputz/controllers/XboxController.py": ["/inputz/Controller.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/OS.py", "/inputz/keys/__init__.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/examples/ClassTest.py": ["/inputz/Devices.py"], "/inputz/keys/__init__.py": ["/inputz/keys/Trigger.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/inputz/handlers/Single.py": ["/inputz/handlers/Handler.py"], "/examples/FunctionTest.py": ["/inputz/Devices.py"], "/examples/ControllerTest.py": ["/inputz/__init__.py", "/inputz/Devices.py"], "/inputz/invokations/Invokation.py": ["/inputz/handlers/Handler.py"], "/inputz/Devices.py": ["/inputz/exceptions/ControllerNotFound.py", "/inputz/Controller.py", "/inputz/controllers/__init__.py"], "/inputz/keys/Button.py": ["/inputz/Input.py"], "/inputz/controllers/__init__.py": ["/inputz/controllers/XboxController.py", "/inputz/controllers/XboxEliteController.py"], "/inputz/Controller.py": ["/inputz/handlers/Contentious.py", "/inputz/handlers/Single.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/invokations/__init__.py"], "/inputz/controllers/XboxEliteController.py": ["/inputz/controllers/__init__.py"], "/inputz/keys/Trigger.py": ["/inputz/Input.py"], "/inputz/invokations/__init__.py": ["/inputz/invokations/Invokation.py"]} |
57,282 | HCI902E18/inputz | refs/heads/master | /inputz/Controller.py | import enum
import platform
import time
from queue import Queue
from time import sleep
import keyboard as keybard
from inputz.handlers.Contentious import Contentious
from inputz.handlers.Single import Single
from .Input import Input
from .KillableThread import KillableThread
from .invokations import Invokation
from .logging import Logger
class Controller(Logger):
"""
Controller
Generic class for each controller to implement.
Spawns reporter thread, thread is used to call methods which listens for button presses.
"""
def __init__(self):
super().__init__()
# Used as thread loop condition
self.__kill = False
# Thread used for reporter
self.killer_thread = 'tronald_dump'
self.__threads = [
KillableThread(name='reporter', target=self.__reporter, args=()),
KillableThread(name=self.killer_thread, target=self.__killer, args=())
]
# List of functions waiting for event to trigger
self.__invocations = []
# Tickrate of the reporter, 0.1 = 10 ticks a second
self._tick_rate = 0.1
# Functions or method called in case of controller disconnection
self.__abort_methods = Queue()
# Property used for thread killing in case of controller disconnection
self.__self_destruct = False
# Used for the controller to run in unsecure mode, which means that the decorated functions or classes
# does not handle controller disconnection
self.__unsecure = False
self.os = self.get_os()
class OS(enum.Enum):
win = 'win'
linux = 'linux'
class Handler(enum.Enum):
contentious = Contentious
single = Single
def __reporter(self) -> None:
"""
Thread method, checks in intervals what button are pressed.
Runs while __killed == False
:return: None
"""
while not self.__kill:
# Start tick
start_time = time.time()
self.__check_keys()
# Calculate the time that the reporter should sleep
sleep_time = self._tick_rate - (time.time() - start_time)
# Handle too slow calculations
if sleep_time > 0:
sleep(sleep_time)
else:
self.log.error(f"Tick took too long, skipping")
overflow = round(abs(sleep_time), 5)
self.log.debug(f"Tick overshoot by {overflow}ms")
def start(self) -> None:
"""
Method used to start all the threads
:return: None
"""
if self.__abort_methods.qsize() == 0 and not self.__unsecure:
self.log.error("No abort method or functions found")
self.log.error("These need to be handled in case of controller disconnection")
self.log.error("OR run the controller in unsecure mode. (device.run_unsecure())")
exit(1)
for thread in self.__threads:
thread.start()
def __killer(self) -> None:
"""
Killer thread
This method is burning dem CPU cycles, but in return it's listening for that escape key
:return: None
"""
try:
while True:
if keybard.is_pressed('Esc') or self.__self_destruct:
self.log.error("WE ARE EXITING NOW!")
self.terminate()
exit(0)
# Not root on linux
except Exception:
pass
def add_thread(self, thread: KillableThread) -> bool:
"""
A contoller may run multiple threads in order to keep track of multiple I/O operations
:param thread: The thread which should be added to the pool
:return: Boolean if the thread is added
"""
if isinstance(thread, KillableThread):
self.__threads.append(thread)
return True
return False
def terminate(self) -> None:
"""
Method used for politely killing reporter threads
:return: None
"""
self.__kill = True
for thread in self.__threads:
# A thread cannot kill it self, but this specific thread kills it self anyway
if thread.name != self.killer_thread:
thread.kill(consequences=True)
def __check_keys(self) -> None:
"""
Checks all properties which is of the instance Input.Input.
If Input is not `None` report that value to functions which is listening for it.
:return: None
"""
# Loops over all properties of self class instance
for key, input_ in self.__dict__.items():
# Checks if property is of instance Input.Input
if isinstance(input_, Input):
# Gets the value from the controller key
input_value = input_.value()
# If key is not `None`, send value to functions which is listening
if input_value is not None:
# Loops over all invocations
for invocation in self.__invocations:
# Checks if invocations is listening for current key
if invocation.is_(key):
# Transmit value to invocation
invocation.transmit(input_value)
def method_listener(self, func: "function", keys: list, handler: Handler = Handler.contentious) -> None:
"""
Method for binding methods from other class instances
:param func: The function to be called
:param keys: Key as string or list
:param handler: The way that the method wants information
:return: None
"""
if isinstance(keys, list):
for key in keys:
self.__bind(func, key, handler)
else:
self.__bind(func, keys, handler)
def listen(self, *keys, handler: Handler = Handler.contentious) -> "function":
"""
Decorator for functions
:param keys: Which keys should trigger the function
:param handler: The way that the method wants information
:return: Decorated function
"""
def decorator(func):
return self.__internal_listen(func, keys, handler)
return decorator
def __internal_listen(self, func: "function", keys: tuple, handler: Handler) -> "function":
"""
Allows controller, to make function calls via reporter
:param func: The function to be called
:param keys: Keys either as string or tuple
:return: Returns the decorated function
"""
if isinstance(keys, tuple):
for key in keys:
self.__bind(func, key, handler)
else:
self.__bind(func, keys, handler)
return func
def __bind(self, func: "function", key: str, handler: Handler) -> None:
"""
Binds the key to the function
:param func: The function to bind
:param key: Key as string
:return: None
"""
handler_instance = handler.value()
self.__invocations.append(Invokation(func, key, handler_instance))
def clear_invocations(self) -> None:
"""
Clears all current bindings
:return: None
"""
while len(self.__invocations) > 0:
self.__invocations.pop()
def kill_state(self) -> bool:
"""
Getter for the private kill variable
:return: is kill running?
"""
return self.__kill
def abort(self) -> None:
"""
Methods which invokes ALL abort method and functions
:return: None
"""
# Sets the controller in self destruct mode so all threads are killed safe-fully
self.__self_destruct = True
# Call all methods in abort queue, called in FIFO order
while self.__abort_methods.qsize() > 0:
# Pop first method or function
func = self.__abort_methods.get()
# Call method or function
func()
def abort_method(self, method: "function") -> None:
"""
Decorator for class methods which should be executed in case of a disconnect
:param method: A method to be run when program aborts
:return: None
"""
self.__abort_methods.put(method)
return
def abort_function(self, func: "function") -> "function":
"""
Decorator for function which should be executed in case of a disconnect
:param func: A function to be run when program aborts
:return: Returns the same function as given as parameter
"""
self.__abort_methods.put(func)
return func
def run_unsecure(self) -> None:
"""
Method which allows the controller to run with no method or functions to handle controller disconnection
:return: None
"""
self.__unsecure = True
def get_os(self):
if platform.system() == 'Windows':
return self.OS.win
elif platform.system() == 'Linux':
return self.OS.linux
raise Exception('MAC NOT SUPPORTED')
| {"/inputz/keys/Joystick.py": ["/inputz/Input.py"], "/examples/XboxController.py": ["/inputz/Devices.py"], "/inputz/__init__.py": ["/inputz/Controller.py", "/inputz/Devices.py", "/inputz/Input.py", "/inputz/invokations/Invokation.py", "/inputz/KillableThread.py", "/inputz/OS.py"], "/examples/EmbedClassTest.py": ["/inputz/Devices.py"], "/inputz/handlers/Contentious.py": ["/inputz/handlers/Handler.py"], "/inputz/controllers/XboxController.py": ["/inputz/Controller.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/OS.py", "/inputz/keys/__init__.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/examples/ClassTest.py": ["/inputz/Devices.py"], "/inputz/keys/__init__.py": ["/inputz/keys/Trigger.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/inputz/handlers/Single.py": ["/inputz/handlers/Handler.py"], "/examples/FunctionTest.py": ["/inputz/Devices.py"], "/examples/ControllerTest.py": ["/inputz/__init__.py", "/inputz/Devices.py"], "/inputz/invokations/Invokation.py": ["/inputz/handlers/Handler.py"], "/inputz/Devices.py": ["/inputz/exceptions/ControllerNotFound.py", "/inputz/Controller.py", "/inputz/controllers/__init__.py"], "/inputz/keys/Button.py": ["/inputz/Input.py"], "/inputz/controllers/__init__.py": ["/inputz/controllers/XboxController.py", "/inputz/controllers/XboxEliteController.py"], "/inputz/Controller.py": ["/inputz/handlers/Contentious.py", "/inputz/handlers/Single.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/invokations/__init__.py"], "/inputz/controllers/XboxEliteController.py": ["/inputz/controllers/__init__.py"], "/inputz/keys/Trigger.py": ["/inputz/Input.py"], "/inputz/invokations/__init__.py": ["/inputz/invokations/Invokation.py"]} |
57,283 | HCI902E18/inputz | refs/heads/master | /inputz/controllers/XboxEliteController.py | from inputz.controllers import XboxController
class XboxEliteController(XboxController):
"""
Xbox controller mappings
"""
@staticmethod
def validate(name: str) -> bool:
"""
Used to validate if the name of the controller matches this controller
:param name: The name of the input controller
:return: bool, if the controller matches
"""
return name == 'Microsoft X-Box One Elite pad'
| {"/inputz/keys/Joystick.py": ["/inputz/Input.py"], "/examples/XboxController.py": ["/inputz/Devices.py"], "/inputz/__init__.py": ["/inputz/Controller.py", "/inputz/Devices.py", "/inputz/Input.py", "/inputz/invokations/Invokation.py", "/inputz/KillableThread.py", "/inputz/OS.py"], "/examples/EmbedClassTest.py": ["/inputz/Devices.py"], "/inputz/handlers/Contentious.py": ["/inputz/handlers/Handler.py"], "/inputz/controllers/XboxController.py": ["/inputz/Controller.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/OS.py", "/inputz/keys/__init__.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/examples/ClassTest.py": ["/inputz/Devices.py"], "/inputz/keys/__init__.py": ["/inputz/keys/Trigger.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/inputz/handlers/Single.py": ["/inputz/handlers/Handler.py"], "/examples/FunctionTest.py": ["/inputz/Devices.py"], "/examples/ControllerTest.py": ["/inputz/__init__.py", "/inputz/Devices.py"], "/inputz/invokations/Invokation.py": ["/inputz/handlers/Handler.py"], "/inputz/Devices.py": ["/inputz/exceptions/ControllerNotFound.py", "/inputz/Controller.py", "/inputz/controllers/__init__.py"], "/inputz/keys/Button.py": ["/inputz/Input.py"], "/inputz/controllers/__init__.py": ["/inputz/controllers/XboxController.py", "/inputz/controllers/XboxEliteController.py"], "/inputz/Controller.py": ["/inputz/handlers/Contentious.py", "/inputz/handlers/Single.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/invokations/__init__.py"], "/inputz/controllers/XboxEliteController.py": ["/inputz/controllers/__init__.py"], "/inputz/keys/Trigger.py": ["/inputz/Input.py"], "/inputz/invokations/__init__.py": ["/inputz/invokations/Invokation.py"]} |
57,284 | HCI902E18/inputz | refs/heads/master | /inputz/OS.py | import platform
class OS(object):
"""
Class used for determining operative system.
"""
WIN = True if platform.system() == 'Windows' else False
MAC = True if platform.system() == 'Darwin' else False
NIX = True if platform.system() == 'Linux' else False
| {"/inputz/keys/Joystick.py": ["/inputz/Input.py"], "/examples/XboxController.py": ["/inputz/Devices.py"], "/inputz/__init__.py": ["/inputz/Controller.py", "/inputz/Devices.py", "/inputz/Input.py", "/inputz/invokations/Invokation.py", "/inputz/KillableThread.py", "/inputz/OS.py"], "/examples/EmbedClassTest.py": ["/inputz/Devices.py"], "/inputz/handlers/Contentious.py": ["/inputz/handlers/Handler.py"], "/inputz/controllers/XboxController.py": ["/inputz/Controller.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/OS.py", "/inputz/keys/__init__.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/examples/ClassTest.py": ["/inputz/Devices.py"], "/inputz/keys/__init__.py": ["/inputz/keys/Trigger.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/inputz/handlers/Single.py": ["/inputz/handlers/Handler.py"], "/examples/FunctionTest.py": ["/inputz/Devices.py"], "/examples/ControllerTest.py": ["/inputz/__init__.py", "/inputz/Devices.py"], "/inputz/invokations/Invokation.py": ["/inputz/handlers/Handler.py"], "/inputz/Devices.py": ["/inputz/exceptions/ControllerNotFound.py", "/inputz/Controller.py", "/inputz/controllers/__init__.py"], "/inputz/keys/Button.py": ["/inputz/Input.py"], "/inputz/controllers/__init__.py": ["/inputz/controllers/XboxController.py", "/inputz/controllers/XboxEliteController.py"], "/inputz/Controller.py": ["/inputz/handlers/Contentious.py", "/inputz/handlers/Single.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/invokations/__init__.py"], "/inputz/controllers/XboxEliteController.py": ["/inputz/controllers/__init__.py"], "/inputz/keys/Trigger.py": ["/inputz/Input.py"], "/inputz/invokations/__init__.py": ["/inputz/invokations/Invokation.py"]} |
57,285 | HCI902E18/inputz | refs/heads/master | /inputz/keys/Trigger.py | from copy import deepcopy
from inputs import InputEvent
from inputz.Input import Input
class Trigger(Input):
"""
Class mapping to X-Box Triggers
"""
def __init__(self, event, **kwargs):
super().__init__(kwargs.get('parse_func', None))
# Triggers might wobble, so this value is to filter those
self.__offset = kwargs.get('offset', 0) / 100
# This is the event the trigger will listen for
self.__event = event
# The interval the event will be within
self.interval = deepcopy(kwargs.get('interval', [0, 255]))
# The current state of the trigger
self.__state = 0
# The last value the trigger reported to functions listen for it
self._last_report = 0
def validate(self, event) -> bool:
"""
Validates if this event is for this trigger
:param event: Event from the controller
:return: bool
"""
if not isinstance(event, InputEvent): return False
return event.code == self.__event
def parse(self, event) -> None:
"""
Parse the event to get data for this trigger.
:param event: The event which data should be extracted from.
:return: None
"""
if not isinstance(event, InputEvent): return
_, _, state_ = super().parse(event)
val_ = 0
# Checks that the event value is between the interval
if self.interval[0] <= state_ <= self.interval[1]:
val_ = state_ / self.interval[1]
# If the value is within the wobble boundary, remove
if val_ < self.__offset:
val_ = 0
self.__state = val_
def value(self) -> float:
"""
Method that returns the value of the trigger.
Returns the value if the value changed since last report
Else report `None`
:return: None or float
"""
if self.__state == self._last_report and self.__state == 0:
return None
if self.parse_func_ is None:
return self._set_last_report(self.__state)
return self.parse_func_(self._set_last_report(self.__state))
| {"/inputz/keys/Joystick.py": ["/inputz/Input.py"], "/examples/XboxController.py": ["/inputz/Devices.py"], "/inputz/__init__.py": ["/inputz/Controller.py", "/inputz/Devices.py", "/inputz/Input.py", "/inputz/invokations/Invokation.py", "/inputz/KillableThread.py", "/inputz/OS.py"], "/examples/EmbedClassTest.py": ["/inputz/Devices.py"], "/inputz/handlers/Contentious.py": ["/inputz/handlers/Handler.py"], "/inputz/controllers/XboxController.py": ["/inputz/Controller.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/OS.py", "/inputz/keys/__init__.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/examples/ClassTest.py": ["/inputz/Devices.py"], "/inputz/keys/__init__.py": ["/inputz/keys/Trigger.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/inputz/handlers/Single.py": ["/inputz/handlers/Handler.py"], "/examples/FunctionTest.py": ["/inputz/Devices.py"], "/examples/ControllerTest.py": ["/inputz/__init__.py", "/inputz/Devices.py"], "/inputz/invokations/Invokation.py": ["/inputz/handlers/Handler.py"], "/inputz/Devices.py": ["/inputz/exceptions/ControllerNotFound.py", "/inputz/Controller.py", "/inputz/controllers/__init__.py"], "/inputz/keys/Button.py": ["/inputz/Input.py"], "/inputz/controllers/__init__.py": ["/inputz/controllers/XboxController.py", "/inputz/controllers/XboxEliteController.py"], "/inputz/Controller.py": ["/inputz/handlers/Contentious.py", "/inputz/handlers/Single.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/invokations/__init__.py"], "/inputz/controllers/XboxEliteController.py": ["/inputz/controllers/__init__.py"], "/inputz/keys/Trigger.py": ["/inputz/Input.py"], "/inputz/invokations/__init__.py": ["/inputz/invokations/Invokation.py"]} |
57,286 | HCI902E18/inputz | refs/heads/master | /inputz/invokations/__init__.py | from .Invokation import Invokation
| {"/inputz/keys/Joystick.py": ["/inputz/Input.py"], "/examples/XboxController.py": ["/inputz/Devices.py"], "/inputz/__init__.py": ["/inputz/Controller.py", "/inputz/Devices.py", "/inputz/Input.py", "/inputz/invokations/Invokation.py", "/inputz/KillableThread.py", "/inputz/OS.py"], "/examples/EmbedClassTest.py": ["/inputz/Devices.py"], "/inputz/handlers/Contentious.py": ["/inputz/handlers/Handler.py"], "/inputz/controllers/XboxController.py": ["/inputz/Controller.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/OS.py", "/inputz/keys/__init__.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/examples/ClassTest.py": ["/inputz/Devices.py"], "/inputz/keys/__init__.py": ["/inputz/keys/Trigger.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/inputz/handlers/Single.py": ["/inputz/handlers/Handler.py"], "/examples/FunctionTest.py": ["/inputz/Devices.py"], "/examples/ControllerTest.py": ["/inputz/__init__.py", "/inputz/Devices.py"], "/inputz/invokations/Invokation.py": ["/inputz/handlers/Handler.py"], "/inputz/Devices.py": ["/inputz/exceptions/ControllerNotFound.py", "/inputz/Controller.py", "/inputz/controllers/__init__.py"], "/inputz/keys/Button.py": ["/inputz/Input.py"], "/inputz/controllers/__init__.py": ["/inputz/controllers/XboxController.py", "/inputz/controllers/XboxEliteController.py"], "/inputz/Controller.py": ["/inputz/handlers/Contentious.py", "/inputz/handlers/Single.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/invokations/__init__.py"], "/inputz/controllers/XboxEliteController.py": ["/inputz/controllers/__init__.py"], "/inputz/keys/Trigger.py": ["/inputz/Input.py"], "/inputz/invokations/__init__.py": ["/inputz/invokations/Invokation.py"]} |
57,287 | HCI902E18/inputz | refs/heads/master | /inputz/Input.py | from copy import deepcopy
from inputs import InputEvent
from .logging import Logger
class Input(Logger):
"""
Input
Base class for all input types
"""
def __init__(self, parse_func=None):
super().__init__()
# The value from last time the input was read
self._last_report = None
if callable(parse_func):
self.parse_func_ = parse_func
else:
self.parse_func_ = None
def validate(self, event: InputEvent) -> Exception:
"""
Checks if current event is related to this input
:param event: The event and data related to
:return: This is just a base class so this will throw exception
"""
raise NotImplemented()
def parse(self, event):
"""
Method used for parsing the event
:param event: The InputEvent
:return: Type, Code And state of the input
"""
if not isinstance(event, InputEvent):
raise Exception('WRONG INPUT TYPE')
return event.ev_type, event.code, event.state
def _set_last_report(self, report):
# Deepcopy is needed in case of vector (list of two elements)
self._last_report = deepcopy(report)
return report
def value(self):
"""
The value of the input
:return: The value of the input
"""
raise NotImplemented()
| {"/inputz/keys/Joystick.py": ["/inputz/Input.py"], "/examples/XboxController.py": ["/inputz/Devices.py"], "/inputz/__init__.py": ["/inputz/Controller.py", "/inputz/Devices.py", "/inputz/Input.py", "/inputz/invokations/Invokation.py", "/inputz/KillableThread.py", "/inputz/OS.py"], "/examples/EmbedClassTest.py": ["/inputz/Devices.py"], "/inputz/handlers/Contentious.py": ["/inputz/handlers/Handler.py"], "/inputz/controllers/XboxController.py": ["/inputz/Controller.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/OS.py", "/inputz/keys/__init__.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/examples/ClassTest.py": ["/inputz/Devices.py"], "/inputz/keys/__init__.py": ["/inputz/keys/Trigger.py", "/inputz/keys/Button.py", "/inputz/keys/Joystick.py"], "/inputz/handlers/Single.py": ["/inputz/handlers/Handler.py"], "/examples/FunctionTest.py": ["/inputz/Devices.py"], "/examples/ControllerTest.py": ["/inputz/__init__.py", "/inputz/Devices.py"], "/inputz/invokations/Invokation.py": ["/inputz/handlers/Handler.py"], "/inputz/Devices.py": ["/inputz/exceptions/ControllerNotFound.py", "/inputz/Controller.py", "/inputz/controllers/__init__.py"], "/inputz/keys/Button.py": ["/inputz/Input.py"], "/inputz/controllers/__init__.py": ["/inputz/controllers/XboxController.py", "/inputz/controllers/XboxEliteController.py"], "/inputz/Controller.py": ["/inputz/handlers/Contentious.py", "/inputz/handlers/Single.py", "/inputz/Input.py", "/inputz/KillableThread.py", "/inputz/invokations/__init__.py"], "/inputz/controllers/XboxEliteController.py": ["/inputz/controllers/__init__.py"], "/inputz/keys/Trigger.py": ["/inputz/Input.py"], "/inputz/invokations/__init__.py": ["/inputz/invokations/Invokation.py"]} |
57,292 | vvtommy/ktouch-csv-converter | refs/heads/master | /phonebook.py | #!/usr/bin/env python
#coding=utf-8
import sys
from ktouch import read_ktouch_phone_book_csv,generate_icard
from optparse import OptionParser
reload(sys)
sys.setdefaultencoding('utf-8')
if __name__ == '__main__':
parser=OptionParser()
# parser.set_usage('转换天宇手机的导出文件为豌豆荚格式,短信请按照收件箱、发件箱、草稿箱分别导出。')
parser.add_option('-p','--phonebook',dest=u'phonebook',
metavar='FILE',help=u'天宇手机的收件箱导出文件',default='phonebook.csv')
parser.add_option('-o','--output',dest=u'output',
metavar='FILE',help=u'生成文件',default='phonebook_for_wandoujia.iCard')
(options,args)=parser.parse_args()
output=open(options.output,'w')
output.write(generate_icard(read_ktouch_phone_book_csv(options.phonebook)))
output.close()
| {"/phonebook.py": ["/ktouch.py"], "/message.py": ["/ktouch.py"]} |
57,293 | vvtommy/ktouch-csv-converter | refs/heads/master | /ktouch.py | #!/usr/bin/env python
#coding=utf-8
# 将旧的时间转换为新的android豌豆荚导出格式的时间
# 2012/11/03 13:18:23 -> 2012.11.05 16:41,20
def convert_time(old_time):
# print '时间:',old_time
tmp=old_time.split(' ')
# print '时间',tmp[1][6:]
return tmp[0].replace('/','.')+' '+tmp[1][:5]+','+tmp[1][6:]
# 两种type:deliver|submit
def convert_message(lines,type=None):
ret=[]
# 跳过首行标志
flag=True
for x in lines:
if flag:
flag=False
continue
line=x.split('\t')
if not line[0] and not line[1] and not line[2]:
print '发生错误',x
continue
# 首先是个固定的头
# sms,deliver,13201691692,,,2012.11.05 16:41,20,短信正文
ret_line='sms,'+(type or 'deliver')+','
# 然后接电话号码
if type is 'submit':
ret_line+=','+line[0]+',,'
elif type is 'deliver':
ret_line+=line[0]+',,,'
else:
ret_line+=',,,'
# 接下来是时间
ret_line+=convert_time(line[1])+','
# 正文
ret_line+=line[2]
ret.append(ret_line)
return ret
def read_ktouch_message_csv(file_path):
try:
f=open(file_path,'rb')
file_buffer=f.read()
f.close()
# 定义输出结果list
ret=[]
# 定义引号计数器
counter=0
# 一行是否开始的标记
start=False
# 当前行的指针
line=[]
# 开始遍历文件,每6个双引号就是一行
for char in file_buffer:
# 如果一行还未开始,则一遇到双引号就是一行开始的时候了
if start is False and char is '"':
start=True
# 如果一行还未开始就直接执行下一个
if not start:
continue
if char is '"':
# 如果遇到双引号,则计数器增加
counter+=1
if counter%6 is 0:
# 保存当前行到结果中
ret.append(''.join(line))
# 开始新行
line=[]
start=False
else:
# 如果遇到的不是双引号,那么就把字符保存到当前行中
line.append(char)
except IOError,e:
print e
return ret
def read_ktouch_phone_book_csv(file):
ret=[]
try:
f=open(file)
for line in f:
line=line.strip()
if line[-3:] != ',,,':
# 略过第一行
continue
info=line.split(',')
ret.append({'name':info[0][1:-1].strip(),'number':info[1][1:-1].strip()})
f.close()
except IOError,e:
print e
return ret
def generate_icard(data):
ret=''
for x in data:
ret+='BEGIN:VCARD\n\
VERSION:3.0\n\
FN:%s\n\
N:;%s;;;\n\
TEL;TYPE=CELL:%s\n\
CATEGORIES:所有联系人\n\
X-WDJ-STARRED:0\n\
END:VCARD\n'%(x['name'],x['name'],x['number'])
return ret
if __name__ == '__main__':
print 'K-Touch Module'
| {"/phonebook.py": ["/ktouch.py"], "/message.py": ["/ktouch.py"]} |
57,294 | vvtommy/ktouch-csv-converter | refs/heads/master | /message.py | #!/usr/bin/env python
#coding=utf-8
import sys
from ktouch import read_ktouch_message_csv,convert_message
from optparse import OptionParser
reload(sys)
sys.setdefaultencoding('utf-8')
if __name__ == '__main__':
parser=OptionParser()
# parser.set_usage('转换天宇手机的导出文件为豌豆荚格式,短信请按照收件箱、发件箱、草稿箱分别导出。')
parser.add_option('-i','--inbox',dest=u'inbox',
metavar='FILE',help=u'天宇手机的收件箱导出文件',default='inbox.csv')
parser.add_option('-t','--outbox',dest=u'outbox',
metavar='FILE',help=u'天宇手机的发件箱导出文件',default='outbox.csv')
parser.add_option('-d','--draft',dest=u'draft',
metavar='FILE',help=u'天宇手机的草稿箱导出文件',default='draft.csv')
parser.add_option('-o','--output',dest=u'output',
metavar='FILE',help=u'生成文件',default='message_for_wandoujia.csv')
(options,args)=parser.parse_args()
outbox_buffer=read_ktouch_message_csv(options.outbox)
outbox_result=convert_message(outbox_buffer,'deliver')
inbox_buffer=read_ktouch_message_csv(options.inbox)
inbox_result=convert_message(inbox_buffer,'submit')
draft_buffer=read_ktouch_message_csv(options.draft)
draft_result=convert_message(draft_buffer)
file_to_write=open(options.output,'w')
for line in (outbox_result+inbox_result+draft_result):
file_to_write.write(line+'\n')
| {"/phonebook.py": ["/ktouch.py"], "/message.py": ["/ktouch.py"]} |
57,298 | fdoubleprime/17scraper | refs/heads/main | /userSettings.py | username17 = None
password17 = None
usernameG = None
passwordG = None
| {"/17scraper.py": ["/utilities.py"], "/utilities.py": ["/userSettings.py"]} |
57,299 | fdoubleprime/17scraper | refs/heads/main | /17scraper.py | import utilities
import selenium.webdriver.support.select as select
driver = utilities.startBrowser()
driver = utilities.login(driver)
expansionSelectorName = 'expansion'
driver.get('https://www.17lands.com/collection')
expansionSelector = select.Select(driver.find_element_by_name(expansionSelectorName))
expansionSelector.select_by_value('KHM')
driver.find_element_by_css_selector('#collection_app > div > div:nth-child(4) > table') | {"/17scraper.py": ["/utilities.py"], "/utilities.py": ["/userSettings.py"]} |
57,300 | fdoubleprime/17scraper | refs/heads/main | /utilities.py | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import userSettings
import mtgSettings
def startBrowser():
driver=webdriver.Chrome('./chromedriver')
return driver
def login(driver):
driver.get('https:\\www.17lands.com\login')
usernameSelector = 'email'
passwordSelector = 'password'
loginSelector = 'submit'
currentSelector = driver.find_element_by_name(usernameSelector)
currentSelector.clear()
currentSelector.send_keys(userSettings.username17)
currentSelector = driver.find_element_by_name(passwordSelector)
currentSelector.clear()
currentSelector.send_keys(userSettings.password17)
currentSelector = driver.find_element_by_name(loginSelector)
currentSelector.click()
return driver | {"/17scraper.py": ["/utilities.py"], "/utilities.py": ["/userSettings.py"]} |
57,301 | codemakeshare/g-mint | refs/heads/master | /tools/lathetask.py | from guifw.abstractparameters import *
from geometry import *
from solids import *
import multiprocessing as mp
import time
import pyclipper
from polygons import *
from gcode import *
class LatheTask(ItemWithParameters):
def __init__(self, model=None, tools=[], viewUpdater=None, **kwargs):
ItemWithParameters.__init__(self, **kwargs)
self.model=model.object
self.patterns=[]
self.path=None
self.output_format = {
"lathe (ZX)": {"mapping": ["Z", "X", "Y"], "scaling":[1.0, -2.0, 0.0]},
"mill (XZ)": {"mapping": ["X", "Z", "Y"], "scaling": [1.0, -1.0, 0.0]}
}
# remap lathe axis for output. For Visualisation, we use x as long axis and y as cross axis. Output uses Z as long axis, x as cross.
#self.axis_mapping=["Z", "X", "Y"]
# scaling factors for output. We use factor -2.0 for x (diameter instead of radius), inverted from negative Y coordinate in viz
#self.axis_scaling = [1.0, -2.0, 0.0]
self.outputFormatChoice= ChoiceParameter(parent=self, name="Output format", choices=list(self.output_format.keys()), value=list(self.output_format.keys())[0])
self.tool = ChoiceParameter(parent=self, name="Tool", choices=tools, value=tools[0])
self.padding=NumericalParameter(parent=self, name="padding", value=0.0, step=0.1)
self.traverseHeight=NumericalParameter(parent=self, name='traverse height', value=self.model.maxv[2]+10, min=self.model.minv[2]-100, max=self.model.maxv[2]+100, step=1.0)
self.offset=NumericalParameter(parent=self, name='offset', value=0.0, min=-100, max=100, step=0.01)
self.waterlevel=NumericalParameter(parent=self, name='waterlevel', value=self.model.minv[2], min=self.model.minv[2], max=self.model.maxv[2], step=1.0)
self.deviation = NumericalParameter(parent=self, name='max. deviation', value=0.1, min=0.0, max=10, step=0.01)
self.minStep=NumericalParameter(parent=self, name="min. step size", value=0.1, min=0.0, max=50.0, step=0.01)
self.viewUpdater=viewUpdater
self.leftBound=NumericalParameter(parent=self, name="left boundary", value=self.model.minv[0], step=0.01)
self.rightBound=NumericalParameter(parent=self, name="right boundary", value=self.model.maxv[0], step=0.01)
self.innerBound=NumericalParameter(parent=self, name="inner boundary", value=0, step=0.01)
self.outerBound=NumericalParameter(parent=self, name="outer boundary", value=self.model.maxv[1], step=0.01)
self.toolSide=ChoiceParameter(parent=self, name="Tool side", choices=["external", "internal"], value = "external")
self.operation=ChoiceParameter(parent=self, name="Operation", choices=["plunge", "turn", "follow"], value = "plunge")
self.direction=ChoiceParameter(parent=self, name="Direction", choices=["right to left", "left to right"], value="right to left")
self.model=model.object
self.sideStep=NumericalParameter(parent=self, name="stepover", value=1.0, min=0.0001, step=0.01)
self.retract = NumericalParameter(parent=self, name="retract", value=1.0, min=0.0001, step=0.1)
self.peckingDepth = NumericalParameter(parent=self, name="pecking depth", value=0.0, min=0.0, step=0.1)
self.peckingRetract = NumericalParameter(parent=self, name="pecking retract", value=1.0, min=0.0, step=0.1)
self.radialOffset = NumericalParameter(parent=self, name='radial offset', value=0.0, min=-100, max=100, step=0.01)
#self.diameter=NumericalParameter(parent=self, name="tool diameter", value=6.0, min=0.0, max=1000.0, step=0.1)
self.precision = NumericalParameter(parent=self, name='precision', value=0.005, min=0.001, max=1, step=0.001)
self.sliceLevel=NumericalParameter(parent=self, name="Slice level", value=0, step=0.1, enforceRange=False, enforceStep=False)
self.rotAxisAdvance = NumericalParameter(parent=self, name="A axis advance", value=0.0, min=0.0, step=0.01)
self.parameters=[self.outputFormatChoice, [self.leftBound, self.rightBound], [self.innerBound, self.outerBound], self.tool, self.toolSide, self.operation, self.direction,
self.sideStep,
self.retract,
self.peckingDepth, #self.peckingRetract,
self.traverseHeight, self.rotAxisAdvance,
self.radialOffset, self.precision, self.sliceLevel]
self.patterns=None
def generatePattern(self):
self.model.get_bounding_box()
#self.model.add_padding((padding,padding,0))
self.slice(addBoundingBox = False)
def slice(self, addBoundingBox = True):
sliceLevel = self.sliceLevel.getValue()
self.patterns = []
print("slicing at ", sliceLevel)
# slice slightly above to clear flat surfaces
slice = self.model.calcSlice(sliceLevel)
for s in slice:
self.patterns.append(s)
def plunge(self, contour):
offset_path = []
dir = 1
start_x = self.leftBound.getValue()
retract = self.retract.getValue()
if self.direction.getValue() == "right to left":
start_x = self.rightBound.getValue()
dir = -1
x=start_x
depth = self.sliceLevel.getValue()
start = -self.traverseHeight.getValue()
innerBound = -self.innerBound.getValue()
while (dir==-1 and x>self.leftBound.getValue()) or (dir==1 and x<self.rightBound.getValue()):
touchPoint = contour.intersectWithLine([x, start], [x, innerBound])
offset_path.append(GPoint(position=(x, start, depth), rapid = True))
if len(touchPoint) > 0:
offset_path.append(GPoint(position=(x, min(touchPoint[0][1], innerBound), depth), rapid = False))
else:
offset_path.append(GPoint(position=(x, innerBound, depth), rapid = False))
# retract and follow contour
# assemble all points between touchpoint and retract point
x_coords = [x, x - dir * retract]
for subpoly in contour.polygons:
for p in subpoly:
if (dir < 0 and p[0] >= x and p[0] <= x + retract) or (dir > 0 and p[0] <= x and p[0] >= x - retract):
x_coords.append(p[0])
x_coords.append(p[0] + 0.00000001)
x_coords.append(p[0] - 0.00000001)
x_coords.sort(reverse = (dir>0) ) # sorting order depends on feed direction
for xfollow in x_coords:
touchPointFollow = contour.intersectWithLine([xfollow, start], [xfollow, innerBound])
if len(touchPointFollow) > 0:
offset_path.append(GPoint(position=(touchPointFollow[0][0], min(touchPointFollow[0][1], innerBound), depth), rapid=False))
else:
offset_path.append(GPoint(position=(xfollow, innerBound, depth), rapid=False))
offset_path.append(GPoint(position=(x - dir*retract, start, depth), rapid = True))
x= x+dir*self.sideStep.getValue()
offset_path.append(GPoint(position=(start_x, start, depth), rapid=True))
return offset_path
def internal_plunge(self, contour):
offset_path = []
dir = 1
start_x = self.leftBound.getValue()
retract = self.retract.getValue()
if self.direction.getValue() == "right to left":
start_x = self.rightBound.getValue()
dir = -1
x=start_x
depth = self.sliceLevel.getValue()
start = -self.traverseHeight.getValue()
outerBound = -self.outerBound.getValue()
while (dir==-1 and x>self.leftBound.getValue()) or (dir==1 and x<self.rightBound.getValue()):
touchPoint = contour.intersectWithLine([x, start], [x, outerBound])
offset_path.append(GPoint(position=(x, start, depth), rapid = True))
if len(touchPoint) > 0:
offset_path.append(GPoint(position=(x, max(touchPoint[0][1], outerBound), depth), rapid = False))
else:
offset_path.append(GPoint(position=(x, outerBound, depth), rapid = False))
# retract and follow contour
# assemble all points between touchpoint and retract point
x_coords = [x, x - dir * retract]
for subpoly in contour.polygons:
for p in subpoly:
if (dir < 0 and p[0] >= x and p[0] <= x + retract) or (dir > 0 and p[0] <= x and p[0] >= x - retract):
x_coords.append(p[0])
x_coords.append(p[0] + 0.00000001)
x_coords.append(p[0] - 0.00000001)
x_coords.sort(reverse = (dir>0) ) # sorting order depends on feed direction
for xfollow in x_coords:
touchPointFollow = contour.intersectWithLine([xfollow, start], [xfollow, outerBound])
if len(touchPointFollow) > 0:
offset_path.append(GPoint(position=(touchPointFollow[0][0], max(touchPointFollow[0][1], outerBound), depth), rapid=False))
else:
offset_path.append(GPoint(position=(xfollow, outerBound, depth), rapid=False))
offset_path.append(GPoint(position=(x - dir*retract, start, depth), rapid = True))
x= x+dir*self.sideStep.getValue()
offset_path.append(GPoint(position=(start_x, start, depth), rapid=True))
return offset_path
def turn(self, contour, x_start, x_end, external=True ):
offset_path = []
depth = self.sliceLevel.getValue()
y = -self.outerBound.getValue()
retract = self.retract.getValue()
sidestep = self.sideStep.getValue()
peckDepth = self.peckingDepth.getValue()
if not external:
retract=-retract
sidestep=-sidestep
y = -self.innerBound.getValue()
while (external and y<-self.innerBound.getValue()) or (not external and y>-self.outerBound.getValue()):
touchPoint = contour.intersectWithLine([self.rightBound.getValue(), y], [self.leftBound.getValue(), y])
if len(touchPoint)>0:
if touchPoint[0][0]<x_start:
offset_path.append(GPoint(position=(x_start, y, depth), rapid = True))
offset_path.append(GPoint(position=(max(touchPoint[0][0], x_end),y, depth), rapid = False))
# assemble all points between touchpoint and retract point
y_coords = [y, y-retract]
for subpoly in contour.polygons:
for p in subpoly:
if (external and p[1] <= y and p[1] >= y-retract) or\
(not external and p[1] >= y and p[1] <= y-retract):
y_coords.append(p[1])
y_coords.append(p[1] + 0.00000001)
y_coords.append(p[1] - 0.00000001)
if external:
y_coords.sort(reverse=True)
else:
y_coords.sort()
for yfollow in y_coords:
touchPointFollow = []
touchPointFollow = contour.intersectWithLine([x_start, yfollow], [x_end, yfollow])
if len(touchPointFollow) > 0:
offset_path.append(GPoint(position=(max(touchPointFollow[0][0], x_end), touchPointFollow[0][1], depth), rapid=False))
else:
offset_path.append(GPoint(position=(x_end, yfollow, depth), rapid=False))
offset_path.append(GPoint(position=(x_start, y-retract, depth), rapid = True))
else:
offset_path.append(GPoint(position=(x_start, y, depth), rapid=True))
offset_path.append(GPoint(position=(x_end, y, depth), rapid=False))
offset_path.append(GPoint(position=(x_end, y-retract, depth), rapid=False))
offset_path.append(GPoint(position=(x_start, y-retract, depth), rapid=True))
y+=sidestep
return offset_path
def follow2(self, contour, external=True):
#assemble all x coordinates
x_coords = [self.rightBound.getValue()-0.00000001, self.rightBound.getValue()+0.00000001, self.leftBound.getValue()-0.00000001, self.leftBound.getValue()+0.00000001]
for subpoly in contour.polygons:
for p in subpoly:
if p[0]>=self.leftBound.getValue() and p[0]<=self.rightBound.getValue():
x_coords.append(p[0])
x_coords.append(p[0]+0.00000001)
x_coords.append(p[0]-0.00000001)
if external:
y = -self.innerBound.getValue()
else:
y = -self.outerBound.getValue()
start = self.rightBound.getValue()
retract = self.retract.getValue()
depth = self.sliceLevel.getValue()
offset_path = []
if self.direction.getValue()=="right to left":
x_coords.sort(reverse=True)
else:
x_coords.sort()
# go to start
offset_path.append(GPoint(position=(x_coords[0], -self.traverseHeight.getValue(), depth), rapid=True))
for x in x_coords:
touchPoint=[]
if external:
touchPoint = contour.intersectWithLine([x, -self.outerBound.getValue()], [x, y])
else:
touchPoint = contour.intersectWithLine([x, -self.innerBound.getValue()], [x, y])
if len(touchPoint) > 0:
offset_path.append(GPoint(position=(touchPoint[0][0], touchPoint[0][1], depth), rapid=False))
else:
if external:
offset_path.append(GPoint(position=(x, -self.innerBound.getValue(), depth), rapid = False))
else:
offset_path.append(GPoint(position=(x, -self.outerBound.getValue(), depth), rapid=False))
# go to traverse depth
offset_path.append(GPoint(position=(x_coords[-1], -self.traverseHeight.getValue(), depth), rapid=True))
return offset_path
def follow(self, contour):
offset_path = []
depth = self.sliceLevel.getValue()
dir = 1
if self.direction.getValue()=="right to left":
dir = -1
y = -self.innerBound.getValue()
start = self.rightBound.getValue()
retract = self.retract.getValue()
# find start point
touchPoint = contour.intersectWithLine([start, -self.outerBound.getValue()], [start, y])
while len(touchPoint)==0:
touchPoint = contour.intersectWithLine([start+10, y], [self.leftBound.getValue(), y])
y-=self.sideStep.getValue()
offset_path.append(GPoint(position=(touchPoint[0][0], touchPoint[0][1], depth), rapid=True))
cd, cp, subpoly, ci = contour.pointDistance([touchPoint[0][0], touchPoint[0][1], depth])
if len(subpoly) == 0:
print("empty subpoly")
return
point_count = 0
last_x = touchPoint[0][0]
while point_count<len(subpoly) and subpoly[ci][0]>=self.leftBound.getValue() and subpoly[ci][0]<=last_x:
p = [x for x in subpoly[ci]]
if p[1]>self.innerBound.getValue():
p[1]=self.innerBound.getValue()
offset_path.append(GPoint(position=p, rapid = False))
last_x = p[0]
ci=(ci-1)
if ci<0:
ci=len(subpoly)-1
point_count+=1
# find end point coming outside-in
touchPoint = contour.intersectWithLine([self.leftBound.getValue(), -self.outerBound.getValue()], [self.leftBound.getValue(), -self.innerBound.getValue()])
if len(touchPoint)>0:
if touchPoint[0][1]>self.innerBound.getValue():
touchPoint[0][1]=self.innerBound.getValue()
offset_path.append(GPoint(position=(touchPoint[0][0], touchPoint[0][1], depth), rapid=False))
# find end point coming left to right
touchPoint = contour.intersectWithLine([self.leftBound.getValue()-10, -self.innerBound.getValue()], [self.leftBound.getValue()+10, -self.innerBound.getValue()])
if len(touchPoint)>0:
if touchPoint[0][1]>self.innerBound.getValue():
touchPoint[0][1]=self.innerBound.getValue()
offset_path.append(GPoint(position=(touchPoint[0][0], touchPoint[0][1], depth), rapid=False))
return offset_path
def applyRotAxisAdvance(self, path, feedAdvance):
angle = 0
new_path = []
p = path[0]
p.rotation = [0,0,0]
current_pos = p.position
new_path.append(p)
for p in path[1:]:
# calculate distance traveled on this line segment
segmentLength = dist(current_pos, p.position)
if segmentLength>0:
if not p.rapid:
# add proportional rotation to 4th axis, to get "feedAdvance" stepover per revolution
angle += segmentLength / feedAdvance * 360
#modify the path points with the angle
p.rotation = [angle, 0, 0]
new_path.append(p)
current_pos = p.position
return new_path
def calcPath(self):
patterns = self.patterns
tool_poly = self.tool.getValue().toolPoly(self.toolSide.getValue())
#invert tool poly, as it's used in a convolution with the outline
for p in tool_poly:
p[0] = -p[0]
p[1] = -p[1]
#if self.toolSide.getValue() == "external": # mirror tool on y axis for external (as we're using the inverted axis to model a lathe)
#
print(tool_poly)
input = PolygonGroup(self.patterns, precision=self.precision.getValue(), zlevel=self.sliceLevel.getValue())
in2 = input.offset(radius=-self.radialOffset.getValue(), rounding=0)
#in2.trimToBoundingBox(self.leftBound.getValue(), -self.outerBound.getValue(), self.rightBound.getValue(), -self.innerBound.getValue() )
contour = in2.convolute(tool_poly)
method = self.operation.getValue()
offset_path=[]
x_start = self.rightBound.getValue()
x_end = self.leftBound.getValue()
if method == "plunge":
if self.toolSide.getValue()=="external":
offset_path = self.plunge(contour)
else:
offset_path = self.internal_plunge(contour)
elif method == "turn":
x_starts = []
x_ends = []
if self.peckingDepth.getValue() > 0:
peck = x_start
start = x_start
while peck>x_end:
peck -= self.peckingDepth.getValue()
if peck<x_end:
peck = x_end
x_starts.append(start)
x_ends.append(peck)
start = peck
else:
x_starts = [x_start]
x_ends = [x_end]
offset_path = []
for start, peck in zip(x_starts, x_ends):
offset_path += self.turn(contour, x_start = start, x_end = peck, external = self.toolSide.getValue()=="external" )
# append full retract to start depth
last = offset_path[-1].position
offset_path.append(GPoint(position=(x_start, last[1], last[2]), rapid=True))
# add return to initial start position of first peck
first = offset_path[0].position
offset_path.append(GPoint(position=(x_start, first[1], first[2]), rapid=True))
elif method == "follow":
offset_path = self.follow2(contour, self.toolSide.getValue()=="external")
#for p in output.polygons:
# offset_path.append(p)
#offset_path = [[GPoint(position=(p[0], p[1], p[2])) for p in segment] for segment in offset_path]
#self.path = GCode([p for segment in offset_path for p in segment])
self.path = GCode(offset_path)
self.path.default_feedrate = 50
format = self.outputFormatChoice.getValue()
# remap lathe axis for output. For Visualisation, we use x as long axis and y as cross axis. Output uses Z as long axis, x as cross.
self.axis_mapping = self.output_format[format]["mapping"]
# scaling factors for output. We use factor -2.0 for x (diameter instead of radius), inverted from negative Y coordinate in viz
self.axis_scaling = self.output_format[format]["scaling"]
self.path.applyAxisMapping(self.axis_mapping)
self.path.applyAxisScaling(self.axis_scaling)
self.path.steppingAxis = 1
if self.rotAxisAdvance.getValue()>0:
self.path.path = self.applyRotAxisAdvance(self.path.path, self.rotAxisAdvance.getValue())
return self.path
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,302 | codemakeshare/g-mint | refs/heads/master | /tools/pathtool.py | from guifw.abstractparameters import *
from gcode import *
from PyQt5 import QtGui
import datetime
import geometry
import traceback
class PathTool(ItemWithParameters):
def __init__(self, path=None, model=None, viewUpdater=None, tool=None, source=None, **kwargs):
ItemWithParameters.__init__(self, **kwargs)
if path is None and self.name.getValue()=="-":
filename= QtGui.QFileDialog.getOpenFileName(None, 'Open file', '', "GCode files (*.ngc)")
self.path = read_gcode(filename[0])
else:
self.path=path
self.viewUpdater=viewUpdater
self.outpaths=[self.path]
self.model=model
self.source = source
self.tool = tool
self.steppingAxis = 2
feedrate=1000
if self.tool is not None:
feedrate =self.tool.feedrate.getValue()
startdepth=0
enddepth=0
outputFile = "gcode/output.ngc"
if model !=None:
startdepth=model.maxv[2]
enddepth=model.minv[2]
if model.filename is not None:
outputFile = model.filename.split(".stl")[0] + ".ngc"
else:
#print self.path.path
try:
if self.path is not None and self.path.getPathLength()>0:
startdepth=max([p.position[2] for p in self.path.get_draw_path() if p.position is not None])
enddepth=min([p.position[2] for p in self.path.get_draw_path() if p.position is not None])
except Exception as e:
print("path error:", e)
traceback.print_exc()
self.startDepth=NumericalParameter(parent=self, name='start depth', value=startdepth, enforceRange=False, step=1)
self.stopDepth=NumericalParameter(parent=self, name='end depth ', value=enddepth, enforceRange=0, step=1)
self.maxDepthStep=NumericalParameter(parent=self, name='max. depth step', value=10.0, min=0.1, max=100, step=1)
self.rampdown=NumericalParameter(parent=self, name='rampdown per loop (0=off)', value=0.1, min=0.0, max=10, step=0.01)
self.traverseHeight=NumericalParameter(parent=self, name='traverse height', value=startdepth+5.0, enforceRange=False, step=1.0)
self.laser_mode = NumericalParameter(parent=self, name='laser mode (power 0-100)', value=0.0, min=0.0, max=100.0, enforceRange=True, step=1.0, callback = self.updateView)
self.depthStepping=ActionParameter(parent=self, name='Depth ramping', callback=self.applyDepthStep)
self.depthSteppingRelRamp = CheckboxParameter(parent=self, name='relative ramping')
self.tabs = NumericalParameter(parent=self, name='Tabs per contour', value=0, min=0, max=20, step=1)
self.tabwidth = NumericalParameter(parent=self, name='Tab width', value=1, min=0, max=20, step=0.1)
self.tabheight = NumericalParameter(parent=self, name='Tab height', value=0.5, min=0, max=20, step=0.1)
self.removeNonCutting=ActionParameter(parent=self, name='Remove non-cutting points', callback=self.removeNoncuttingPoints)
self.invertPath=ActionParameter(parent=self, name='invert path', callback=self.applyInvertPath)
self.clean=ActionParameter(parent=self, name='clean paths', callback=self.cleanColinear)
self.smooth=ActionParameter(parent=self, name='smooth path', callback=self.fitArcs)
self.precision = NumericalParameter(parent=self, name='precision', value=0.005, min=0.001, max=1, step=0.001)
self.trochoidalDiameter=NumericalParameter(parent=self, name='tr. diameter', value=3.0, min=0.0, max=100, step=0.1)
self.trochoidalStepover=NumericalParameter(parent=self, name='tr. stepover', value=1.0, min=0.1, max=5, step=0.1)
self.trochoidalOrder=NumericalParameter(parent=self, name='troch. order', value=0.0, min=0, max=100000, step=1)
self.trochoidalSkip=NumericalParameter(parent=self, name='skip', value=1.0, min=1, max=100000, step=1)
self.trochoidalOuterDist=NumericalParameter(parent=self, name='outer dist', value=1.0, min=0, max=100000, step=1)
self.trochoidalMilling = ActionParameter(parent=self, name='trochoidal', callback=self.calcTrochoidalMilling)
self.feedrate=NumericalParameter(parent=self, name='default feedrate', value=feedrate, min=1, max=5000, step=10, callback=self.updateView)
self.plunge_feedrate = NumericalParameter(parent=self, name='plunge feedrate', value=feedrate/2.0, min=1, max=5000,
step=10, callback=self.updateView)
self.filename=TextParameter(parent=self, name="output filename", value=outputFile)
self.saveButton=ActionParameter(parent=self, name='Save to file', callback=self.save)
self.appendButton=ActionParameter(parent=self, name='append from file', callback=self.appendFromFile)
self.estimatedTime=TextParameter(parent=self, name='est. time', editable=False)
self.estimatedDistance=TextParameter(parent=self, name='distance', editable=False)
self.parameters=[self.startDepth,
self.stopDepth,
self.maxDepthStep,
self.rampdown,
self.traverseHeight,
self.laser_mode,
[self.depthStepping, self.depthSteppingRelRamp],
[self.tabs, self.tabwidth, self.tabheight],
[self.removeNonCutting,
self.invertPath],
[self.clean, self.smooth, self.precision],
[self.trochoidalDiameter, self.trochoidalStepover],
[self.trochoidalOrder, self.trochoidalSkip],
self.trochoidalOuterDist ,
self.trochoidalMilling,
self.feedrate, self.plunge_feedrate,
self.filename,
self.saveButton,
self.appendButton,
self.estimatedTime,
self.estimatedDistance]
self.updateView()
def updatePath(self, path):
self.path = path
self.outpaths=[self.path]
self.updateView()
def applyInvertPath(self):
if len(self.outpaths)==0:
self.path.outpaths=GCode()
self.outpaths.combinePath(self.path.path)
inpath = self.outpaths
pathlet = []
invertedPath = []
preamble = []
for path in inpath:
for p in path.path:
if p.position is not None:
break
else:
print("pre:", p.to_output())
preamble.append(p)
invertedPath+=preamble
for path in reversed(inpath):
for p in reversed(path.get_draw_path(interpolate_arcs=True)):
if p.position is not None: #only append positional points
"point:", p.to_output()
invertedPath.append(p)
self.outpaths = [GCode(path=invertedPath)]
self.updateView()
def cleanColinear(self):
if len(self.outpaths)==0:
self.path.outpaths=GCode()
self.path.outpaths.combinePath(self.path.path)
inpath=self.outpaths
precision = self.precision.getValue()
smoothPath = []
pathlet = []
for path in inpath:
for p in path.path:
pathlet.append(p)
if len(pathlet)<=2:
continue
# check for colinearity
max_error, furthest_point = path_colinear_error([p.position for p in pathlet])
if max_error< precision:
# if colinear, keep going
print("colinear:", len(pathlet), max_error)
pass
else: #if not colinear, check if the problem is at start or end
if len(pathlet)==3: # line doesn't start colinearly - drop first point
print("drop point")
smoothPath.append(pathlet.pop(0))
else: # last point breaks colinearity - append segment up to second-last point
print("append shortened path", len(pathlet), max_error, furthest_point)
smoothPath.append(pathlet[0])
smoothPath.append(pathlet[-2])
pathlet = pathlet[-1:]
smoothPath+=pathlet # append last remaining points
self.outpaths=[GCode(path=smoothPath)]
self.updateView()
def fitArcs(self, dummy=False, min_point_count = 5, max_radius = 1000.0):
if len(self.outpaths)==0:
self.path.outpaths=GCode()
self.path.outpaths.combinePath(self.path.path)
inpath=self.outpaths
print("min point count", min_point_count)
precision = self.precision.getValue()
smoothPath = []
pathlet = []
center = None
radius = 0
direction = "02"
for path in inpath:
for p in path.path:
if p.position is None:
continue
if len(pathlet) < 3: #need at least 3 points to start circle
pathlet.append(p)
# compute center with the first 3 points
elif len(pathlet)==3:
#check if points are in horizontal plane
if pathlet[0].position[2] == pathlet[1].position[2] and pathlet[1].position[2]==pathlet[2].position[2]:
center, radius = findCircleCenter(pathlet[0].position, pathlet[1].position, pathlet[2].position)
else:
center = None
if center is not None:
radius = dist(center, pathlet[0].position)
# check if points are colinear or not in plane, and drop first point
if center is None or radius > max_radius:
print("colinear, drop point")
smoothPath.append(pathlet.pop(0))
center=None
pathlet.append(p)
print(len(pathlet))
else:
# check if following points are also on the same arc
new_center, new_radius = findCircleCenter(pathlet[0].position, pathlet[int(len(pathlet) / 2)].position, p.position)
midpoints = [mid_point(pathlet[i].position, pathlet[i+1].position) for i in range(0, len(pathlet)-1)]
midpoints.append(mid_point(pathlet[-1].position, p.position))
#if abs(dist(p.position, center) - radius) < precision and \
if new_center is not None and \
p.position[2] == pathlet[0].position[2] and\
max([dist(mp, new_center)-new_radius for mp in midpoints]) < precision and \
max([abs(dist(ap.position, new_center) - new_radius) for ap in pathlet]) < precision and\
scapro(diff(pathlet[0].position, center), diff(p.position,center))>0.5:
center = new_center
radius = new_radius
pathlet.append(p)
else:
if len(pathlet)>min_point_count:
# create arc
print("making arc", len(pathlet))
#center_side = scapro(diff(pathlet[int(len(pathlet)/2)].position, pathlet[0].position), diff(center, pathlet[0].position))
center_side = isLeft(pathlet[0].position, pathlet[int(len(pathlet)/2)].position, center)
if center_side < 0:
direction = "02"
print(direction, center_side)
else:
direction = "03"
print(direction, center_side)
arc = GArc(position = pathlet[-1].position,
ij = [center[0] - pathlet[0].position[0], center[1]-pathlet[0].position[1]],
arcdir = direction)
smoothPath.append(pathlet[0])
smoothPath.append(arc)
center = None
pathlet = [p]
else:
#print("not arc, flush", len(pathlet))
smoothPath+=pathlet
pathlet=[p]
center = None
smoothPath+=pathlet # append last remaining points
self.outpaths=[GCode(path=smoothPath)]
self.updateView()
def getCompletePath(self):
completePath = GCode(path=[])
completePath.default_feedrate=self.feedrate.getValue()
completePath.laser_mode = (self.laser_mode.getValue() > 0.1)
completePath.laser_power = self.laser_mode.getValue()*10
print("gCP lasermode", completePath.laser_mode, self.laser_mode.getValue())
for path in self.outpaths:
completePath.combinePath(path)
return completePath
def updateView(self, val=None):
#for line in traceback.format_stack():
# print(line.strip())
if self.viewUpdater!=None:
print("pt:", self.tool)
try:
self.viewUpdater(self.getCompletePath(), tool=self.tool)
except Exception as e:
print(e)
self.updateEstimate()
def updateEstimate(self, val=None):
if self.path is None:
return
self.path.default_feedrate = self.feedrate.getValue()
estimate = None
estimate = self.getCompletePath().estimate()
print(estimate)
self.estimatedTime.updateValue("%s (%s)"%(str(datetime.timedelta(seconds=int(estimate[1]*60))),
str(datetime.timedelta(seconds=int(estimate[5]*60)))))
self.estimatedDistance.updateValue("{:.1f} (c {:.0f})".format(estimate[0], estimate[3], estimate[4]))
def appendFromFile(self):
filename= QtGui.QFileDialog.getOpenFileName(None, 'Open file', '', "GCode files (*.ngc)")
new_path =read_gcode(filename)
self.path.appendPath(new_path)
self.outpaths = [self.path]
self.updateView()
def save(self):
completePath=self.getCompletePath()
completePath.default_feedrate=self.feedrate.getValue()
completePath.laser_mode = (self.laser_mode.getValue()>0.5)
completePath.write(self.filename.getValue())
self.updateEstimate()
def segmentPath(self, path):
buffered_points = [] # points that need to be finished after rampdown
# split into segments of closed loops, or separated by rapids
segments = []
for p in path:
# buffer points to detect closed loops (for ramp-down)
if p.position is not None:
if p.rapid: #flush at rapids
if len(buffered_points)>0:
segments.append(buffered_points)
buffered_points = []
buffered_points.append(p)
# detect closed loops,
if (len(buffered_points) > 2 and dist2D(buffered_points[0].position, p.position) < 0.00001):
segments.append(buffered_points)
buffered_points = []
if len(buffered_points)>0:
segments.append(buffered_points)
buffered_points = []
return segments
def applyTabbing(self, segment, tabs, tabwidth, tabheight):
seg_len = polygon_closed_length2D(segment)
if seg_len<=tabs*tabwidth:
return
for i in range(0, tabs):
length = i * seg_len / tabs
#print(length, seg_len)
i1, p = polygon_point_at_position(segment, length)
height = p[2]
segment.insert(i1, GPoint(position = [x for x in p]))
p[2] = height + tabheight
segment.insert(i1+1, GPoint(position=[x for x in p]))
i2, p = polygon_point_at_position(segment, length+tabwidth)
# elevate all intermediate points
for i in range(i1+1, i2):
segment[i].position[2]=height+tabheight
p[2] = height + tabheight
segment.insert(i2, GPoint(position=[x for x in p]))
p[2] = height
segment.insert(i2+1, GPoint(position=[x for x in p]))
def applyRampDown(self, segment, previousCutDepth, currentDepthLimit, rampdown, relative_ramping = False, axis = 2, axis_scaling = 1):
lastPoint=None
output = []
if relative_ramping:
seg_len = polygon_closed_length2D(segment)
else:
seg_len = 1.0 # use constant for absolute ramping
print("segment length:", seg_len, "order:", segment[0].order, segment[0].dist_from_model)
#check if this is a closed segment:
if dist2D(segment[0].position, segment[-1].position)<0.0001:
# ramp "backwards" to reach target depth at start of segment
ramp = []
sl = len(segment)
pos = sl - 1
currentDepth = min([p.position[axis]/axis_scaling for p in segment]) #get deepest point in segment
while currentDepth < previousCutDepth:
p = segment[pos]
# length of closed polygon perimeter
#ignore rapids during ramp-down
if not p.rapid:
nd = max(p.position[axis]/axis_scaling, currentDepthLimit)
is_in_contact = True
dist = dist2D(segment[pos].position, segment[(pos+1)%sl].position)
currentDepth += dist * (rampdown/seg_len) # spiral up
if (nd<currentDepth):
nd = currentDepth
is_in_contact=False
newpoint = [x for x in p.position]
newpoint[axis] = nd * axis_scaling
ramp.append(GPoint(position=newpoint, rapid=p.rapid,
inside_model=p.inside_model, in_contact=is_in_contact, axis_mapping = p.axis_mapping, axis_scaling=p.axis_scaling))
pos = (pos-1+sl) % sl
p=ramp[-1]
newpoint = [x for x in p.position]
newpoint[axis] = self.traverseHeight.getValue() * axis_scaling
output.append(GPoint(position=newpoint, rapid=True,
inside_model=p.inside_model, in_contact=False, axis_mapping = p.axis_mapping, axis_scaling=p.axis_scaling))
for p in reversed(ramp):
output.append(p)
for p in segment[1:]:
output.append(p)
p=segment[-1]
newpoint = [x for x in p.position]
newpoint[axis] = self.traverseHeight.getValue() * axis_scaling
output.append(GPoint(position=newpoint, rapid=True,
inside_model=p.inside_model, in_contact=False, axis_mapping = p.axis_mapping, axis_scaling=p.axis_scaling))
else: # for open segments, apply forward ramping
lastPoint = None
for p in segment:
nd = max(p.position[2], currentDepthLimit)
is_in_contact = True
# check if rampdown is active, and we're below previously cut levels, then limit plunge rate accordingly
if not p.rapid and rampdown != 0 and nd < previousCutDepth and lastPoint != None:
dist = dist2D(p.position, lastPoint.position)
lastPointDepth = min(lastPoint.position[axis]/axis_scaling, previousCutDepth)
if (lastPointDepth - nd) > dist * rampdown: # plunging to deeply - need to reduce depth for this point
nd = lastPointDepth - dist * rampdown;
is_in_contact = False
# buffer this point to finish closed path at currentDepthLimit
newpoint = [x for x in p.position]
newpoint[axis] = nd * axis_scaling
output.append(GPoint(position=newpoint, rapid=p.rapid,
inside_model=p.inside_model, in_contact=is_in_contact, axis_mapping = p.axis_mapping, axis_scaling=p.axis_scaling))
lastPoint = output[-1]
return output
def applyStepping(self, segment, currentDepthLimit, finished, axis = 2, axis_scaling = 1):
output = []
for p in segment:
# is_in_contact=p.in_contact
is_in_contact = True
nd = p.position[axis] / axis_scaling
if nd < currentDepthLimit:
nd = currentDepthLimit
is_in_contact = False;
finished = False
newpoint = [x for x in p.position]
newpoint[axis] = axis_scaling * nd
output.append(GPoint(position=newpoint, rapid=p.rapid,
inside_model=p.inside_model, in_contact=is_in_contact, axis_mapping = p.axis_mapping, axis_scaling=p.axis_scaling))
return output, finished
def applyDepthStep(self):
print("apply depth stepping")
self.outpaths=[]
finished=False
depthStep=self.maxDepthStep.getValue()
currentDepthLimit=self.startDepth.getValue()-depthStep
endDepth=self.stopDepth.getValue()
relRamping = self.depthSteppingRelRamp.getValue()
if currentDepthLimit<endDepth:
currentDepthLimit=endDepth
previousCutDepth=self.startDepth.getValue()
rampdown=self.rampdown.getValue()
lastPoint=None
# split into segments of closed loops, or separated by rapids
segments = self.segmentPath(self.path.path)
axis = self.path.steppingAxis
axis_scaling = self.path.path[0].axis_scaling[self.path.steppingAxis]
print("axis:", axis, "scaling: ",axis_scaling)
while not finished:
finished=True
newpath=[]
prev_segment = None
for s in segments:
segment_output, finished = self.applyStepping(segment = s, currentDepthLimit = currentDepthLimit, finished=finished, axis = axis,
axis_scaling = axis_scaling)
if (rampdown!=0) and len(segment_output)>3:
if prev_segment is None or closest_point_on_open_polygon(s[0].position, prev_segment)[0] > self.tool.diameter.getValue()/2.0:
segment_output = self.applyRampDown(segment_output, previousCutDepth, currentDepthLimit, rampdown, relRamping, self.path.steppingAxis, axis_scaling)
if self.tabs.getValue()>0:
self.applyTabbing(segment_output, self.tabs.getValue(), self.tabwidth.getValue(), self.tabheight.getValue())
for p in segment_output:
newpath.append(p)
if prev_segment is None:
prev_segment = [p.position for p in s]
else:
prev_segment += [p.position for p in s]
if currentDepthLimit<=endDepth:
finished=True
previousCutDepth=currentDepthLimit
currentDepthLimit-=depthStep
if currentDepthLimit<endDepth:
currentDepthLimit=endDepth
self.outpaths.append(GCode(newpath))
self.updateView()
def removeNoncuttingPoints(self):
new_paths=[]
skipping=False
for path_index, path in enumerate(self.outpaths):
if path_index==0:
new_paths.append(path)
else:
newpath=[]
for p_index, p in enumerate(path):
# check if previous layer already got in contact with final surface
if self.path.outpaths[path_index-1][p_index].in_contact:
if not skipping:
# skip point at safe traverse depth
newpath.append(GPoint(position=(p.position[0], p.position[1], self.traverseHeight.getValue()), rapid=True, inside_model=p.inside_model, in_contact=False))
skipping=True
else:
if skipping:
newpath.append(GPoint(position=(p.position[0], p.position[1], self.traverseHeight.getValue()), rapid=True, inside_model=p.inside_model, in_contact=p.in_contact))
skipping=False
#append point to new output
newpath.append(GPoint(position=(p.position[0], p.position[1], p.position[2]), rapid=p.rapid, inside_model=p.inside_model, in_contact=p.in_contact))
new_paths.append(GCode(newpath))
self.outpaths=new_paths
self.updateView()
def calcTrochoidalMilling(self):
new_paths=[]
lastPoint = None
radius = self.trochoidalDiameter.getValue()/2.0
distPerRev = self.trochoidalStepover.getValue()
rampdown=self.rampdown.getValue()
steps_per_rev = 50
stock_poly = None
if self.source is not None:
stock_poly = self.source.getStockPolygon()
#for path_index, path in enumerate(self.path.path):
newpath=[]
angle = 0
for p_index, p in enumerate(self.path.path):
# when plunging, check if we already cut this part before
cutting = True
plunging = False
for cp in self.path.path[0:p_index]:
if cp.position is None or p.position is None:
continue;
if lastPoint is not None and lastPoint.position[2]>p.position[2] \
and geometry.dist(p.position, cp.position) < min(i for i in [radius, cp.dist_from_model] if i is not None ):
cutting = False
if p.rapid or p.order>self.trochoidalOrder.getValue() or p.dist_from_model< self.trochoidalOuterDist.getValue() or not cutting :
newpath.append(GPoint(position = (p.position), rapid = p.rapid, inside_model=p.inside_model, in_contact=p.in_contact))
else:
if p.order%self.trochoidalSkip.getValue()==0: #skip paths
if lastPoint is not None:
if lastPoint.position[2] > p.position[2]:
plunging = True
else:
plunging = False
dist=sqrt((p.position[0]-lastPoint.position[0])**2 + (p.position[1]-lastPoint.position[1])**2 + (p.position[2]-lastPoint.position[2])**2)
distPerRev = self.trochoidalStepover.getValue()
if plunging:
dradius = radius
if p.dist_from_model is not None:
dradius = min(min(radius, p.dist_from_model), self.tool.diameter.getValue()/2.0)
if rampdown>0.0:
distPerRev = rampdown*(dradius*2.0*pi)
steps = int(float(steps_per_rev)*dist/distPerRev)+1
dradius = 0.0
for i in range(0, steps):
angle -= (dist/float(distPerRev) / float(steps)) * 2.0*PI
dradius = radius
bore_expansion = False
if p.dist_from_model is not None and lastPoint.dist_from_model is not None:
dradius = min(radius, lastPoint.dist_from_model*(1.0-(float(i)/steps)) + p.dist_from_model*(float(i)/steps))
if p.dist_from_model is not None and lastPoint.dist_from_model is None:
dradius = min(radius, p.dist_from_model)
# if plunging and radius is larger than tool diameter, bore at smaller radius and expand out
if plunging:
if dradius>self.tool.diameter.getValue():
dradius = self.tool.diameter.getValue()/2.0
bore_expansion = True
x = lastPoint.position[0]*(1.0-(float(i)/steps)) + p.position[0]*(float(i)/steps) + dradius * sin(angle)
y = lastPoint.position[1]*(1.0-(float(i)/steps)) + p.position[1]*(float(i)/steps) + dradius * cos(angle)
z = lastPoint.position[2]*(1.0-(float(i)/steps)) + p.position[2]*(float(i)/steps)
cutting = True
if stock_poly is not None and not stock_poly.pointInside((x, y, z)):
cutting = False
for cp in self.path.path[0:p_index]:
if cp.dist_from_model is not None and geometry.dist((x, y, z), cp.position) < min(radius, cp.dist_from_model) - 0.5*self.trochoidalStepover.getValue():
cutting = False
if cutting:
feedrate=None
if plunging:
feedrate=self.plunge_feedrate.getValue()
newpath.append(GPoint(position=(x, y, z), rapid=p.rapid, inside_model=p.inside_model,in_contact=p.in_contact, feedrate = feedrate))
if bore_expansion:
distPerRev = self.trochoidalStepover.getValue()
dist = min(radius, p.dist_from_model) - dradius + distPerRev
steps = int(float(steps_per_rev) * (dist / distPerRev) )
for i in range(0, steps):
angle -= (dist / float(distPerRev) / float(steps)) * 2.0 * PI
dradius += dist/steps
if dradius>p.dist_from_model:
dradius=p.dist_from_model
x = p.position[0] + dradius * sin(angle)
y = p.position[1] + dradius * cos(angle)
z = p.position[2]
cutting = True
if stock_poly is not None and not stock_poly.pointInside((x, y, z)):
cutting = False
if cutting:
newpath.append(GPoint(position = (x, y, z), rapid = p.rapid, inside_model=p.inside_model, in_contact=p.in_contact))
lastPoint = p
#remove non-cutting points
# cleanpath=[]
# for p in newpath:
# cutting = True
# for cp in cleanpath:
# if geometry.dist(p.position, cp.position) < min(radius, cp.dist_from_model):
# cutting = False
# if cutting:
# cleanpath.append(p)
new_paths.append(GCode(newpath))
self.outpaths=new_paths
self.updateView()
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,303 | codemakeshare/g-mint | refs/heads/master | /tools/textengrave.py | from guifw.abstractparameters import *
from gcode import *
import re
from .milltask import SliceTask
import svgparse
from svgpathtools import wsvg, Line, QuadraticBezier, Path
from freetype import Face
def tuple_to_imag(t):
return t[0] + t[1] * 1j
class TextEngraveTask(SliceTask):
def __init__(self, model=None, tools=[], viewUpdater=None, **kwargs):
SliceTask.__init__(self, **kwargs)
#self.model=model.object
self.patterns=[]
self.path=None
self.textInput = TextParameter(parent=self, name="input text", value="text")
self.fontsize = NumericalParameter(parent=self, name='font size', value=14, min=1, max=1000, step=1.0)
self.font = FileParameter(parent=self, name="font", value = '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', fileSelectionPattern="TTF font (*.ttf)")
self.tool = ChoiceParameter(parent=self, name="Tool", choices=tools, value=tools[0])
self.direction = ChoiceParameter(parent=self, name="Direction", choices=["inside out", "outside in"], value="outside in")
self.toolSide = ChoiceParameter(parent=self, name="Tool side", choices=["external", "internal"],
value="internal")
self.traverseHeight=NumericalParameter(parent=self, name='traverse height', value=0.1, min=0, max=100, step=1.0)
self.offset=NumericalParameter(parent=self, name='offset', value=0.0, min=-100, max=100, step=0.01)
self.viewUpdater=viewUpdater
self.charSpacing = NumericalParameter(parent = self, name = "character spacing", value = 0, min = 0, max = 1000)
self.border_height = NumericalParameter(parent = self, name = "border height", value = 0, min = 0, max = 1000)
self.border_width = NumericalParameter(parent=self, name="border width", value=0, min=0, max=1000)
self.border_radius = NumericalParameter(parent=self, name="border radius", value=0, min=0, max=1000)
self.border_depth = NumericalParameter(parent=self, name="border radius", value=0, min=0, max=1000)
self.leftBound=NumericalParameter(parent=self, name="left boundary", value=0, step=0.01)
self.rightBound=NumericalParameter(parent=self, name="right boundary", value=0, step=0.01)
self.innerBound=NumericalParameter(parent=self, name="inner boundary", value=0, step=0.01)
self.outerBound=NumericalParameter(parent=self, name="outer boundary", value=0, step=0.01)
self.sliceIter = NumericalParameter(parent=self, name="iterations", value=1, step=1, enforceRange=False,
enforceStep=True)
self.sideStep=NumericalParameter(parent=self, name="stepover", value=0.0, min=0.0001, step=0.01)
self.radialOffset = NumericalParameter(parent=self, name='radial offset', value=0.0, min=-100, max=100, step=0.01)
#self.diameter=NumericalParameter(parent=self, name="tool diameter", value=6.0, min=0.0, max=1000.0, step=0.1)
self.precision = NumericalParameter(parent=self, name='precision', value=0.005, min=0.001, max=1, step=0.001)
self.parameters = [self.textInput, self.fontsize, self.font, self.charSpacing, self.tool, [self.stockMinX, self.stockMinY], [self.stockSizeX, self.stockSizeY], self.direction, self.toolSide, self.sideStep, self.traverseHeight,
self.radialOffset,
self.pathRounding, self.precision, self.sliceIter,
self.border_width, self.border_height, self.border_radius, self.border_depth]
self.patterns = None
self.face = Face(self.font.getValue())
self.face.set_char_size(48 * 64)
def generateCharacter(self, character='a', pos = [0,0, 0.0, 0.0], scaling = 2.54 / 72.0 ):
# adapted from https://medium.com/@femion/text-to-svg-paths-7f676de4c12b
self.face.load_char(character)
outline = self.face.glyph.outline
y = [t[1] for t in outline.points]
# flip the points
outline_points = [(p[0], - p[1]) for p in outline.points]
start, end = 0, 0
paths = []
for i in range(len(outline.contours)):
contour = []
end = outline.contours[i]
points = outline_points[start:end + 1]
points.append(points[0])
tags = outline.tags[start:end + 1]
tags.append(tags[0])
segments = [[points[0], ], ]
for j in range(1, len(points)):
segments[-1].append(points[j])
if tags[j] and j < (len(points) - 1):
segments.append([points[j], ])
for segment in segments:
if len(segment) == 2:
contour.append(Line(start=tuple_to_imag(segment[0]),
end=tuple_to_imag(segment[1])))
elif len(segment) == 3:
contour.append(QuadraticBezier(start=tuple_to_imag(segment[0]),
control=tuple_to_imag(segment[1]),
end=tuple_to_imag(segment[2])))
elif len(segment) == 4:
C = ((segment[1][0] + segment[2][0]) / 2.0,
(segment[1][1] + segment[2][1]) / 2.0)
contour.append(QuadraticBezier(start=tuple_to_imag(segment[0]),
control=tuple_to_imag(segment[1]),
end=tuple_to_imag(C)))
contour.append(QuadraticBezier(start=tuple_to_imag(C),
control=tuple_to_imag(segment[2]),
end=tuple_to_imag(segment[3])))
start = end + 1
path = Path(*contour)
segPath = []
NUM_SAMPLES = 100
for i in range(NUM_SAMPLES):
p = path.point(i /(float(NUM_SAMPLES)-1))
segPath.append([p.real*scaling + pos[0], -p.imag * scaling + pos[1], 0+pos[2]])
paths.append(segPath)
return paths
def generatePattern(self):
scaling = 25.4 / 72.0 / 64.0 # freetype dimensions are in points, 1/72 of an inch. Convert to millimeters...
self.face = Face(self.font.getValue())
self.face.set_char_size(self.fontsize.getValue() * 64)
slot = self.face.glyph
self.patterns=[]
pos = [0.0, 0.0, 0.0]
last_char = None
for c in self.textInput.getValue():
kerning = self.face.get_kerning(" ", " ")
if last_char is not None:
kerning = self.face.get_kerning(last_char, c)
print ("kerning ", last_char, c, kerning.x, slot.advance.x)
last_char = c
if self.charSpacing.getValue() == 0 :
pos[0] += (kerning.x * scaling)
else:
pos[0] += self.charSpacing.getValue()
paths=self.generateCharacter(character = c, pos = pos, scaling = scaling)
pos[0]+=slot.advance.x * scaling
for p in paths:
self.patterns.append(p)
self.model_minv, self.model_maxv = polygon_bounding_box([p for pattern in self.patterns for p in pattern ])
self.stockMinX.updateValue(self.model_minv[0])
self.stockMinY.updateValue(self.model_minv[1])
self.stockSizeX.updateValue(self.model_maxv[0] - self.model_minv[0])
self.stockSizeY.updateValue(self.model_maxv[1] - self.model_minv[1])
print(self.patterns)
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,304 | codemakeshare/g-mint | refs/heads/master | /gcode_editor.py | from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.Qsci import *
import gcode
class QsciGcodeLexer(QsciLexerCPP):
def keywords(self, index):
keywords = QsciLexerCPP.keywords(self, index) or ''
# primary keywords
if index == 1:
return 'G' + 'M' + "F"
# secondary keywords
if index == 2:
return "X"+"Y"+"Z"+"I"+"J"
# doc comment keywords
if index == 3:
return keywords
# global classes
if index == 4:
return keywords
return keywords
class GcodeEditorWidget(QWidget):
def __init__(self, object_viewer=None):
QWidget.__init__(self)
self.lexers={"ngc":QsciGcodeLexer()}
self.suffixToLexer={"ngc":"ngc"}
self.object_viewer = object_viewer
self.layout = QVBoxLayout()
self.setLayout(self.layout)
self.label = QLabel()
self.editor = QsciScintilla()
self.configureEditor(self.editor)
self.layout.addWidget(self.label)
self.layout.addWidget(self.editor)
self.editor.selectionChanged.connect(self.onSelectionChanged)
self.editor.textChanged.connect(self.onTextChanged)
self.pathTool = None
self.editingFlag = False
def setObjectViewer(self, object_viewer):
self.object_viewer = object_viewer
def setPathTool(self, path):
self.pathTool = path
def onSelectionChanged(self):
selection = self.editor.getSelection()
if self.object_viewer is not None:
self.object_viewer.setSelection(selection[0], selection[2])
def onTextChanged(self):
self.editingFlag=True
if self.pathTool is not None:
print ("..")
self.pathTool.updatePath( gcode.parse_gcode(self.getText()))
self.editingFlag=False
def configureEditor(self, editor):
self.__lexer = self.lexers["ngc"]
editor.setLexer(self.__lexer)
editor.setMarginType(1, QsciScintilla.TextMargin)
editor.setMarginType(0, QsciScintilla.SymbolMargin)
editor.setMarginMarkerMask(1, 0b1111)
editor.setMarginMarkerMask(0, 0b1111)
editor.setMarginsForegroundColor(QColor("#ffFF8888"))
editor.setUtf8(True) # Set encoding to UTF-8
#editor.indicatorDefine(QsciScintilla.FullBoxIndicator, 0)
editor.indicatorDefine(QsciScintilla.BoxIndicator, 0)
editor.setAnnotationDisplay(QsciScintilla.AnnotationStandard)
def highlightLine(self, line_number, refresh = False):
if self.editingFlag: # don't update text if a path tool is set, and we're in editing mode
return
marginTextStyle = QsciStyle()
marginTextStyle.setPaper(QColor("#ffFF8888"))
self.editor.blockSignals(True)
self.editor.setCursorPosition(line_number, 0)
self.editor.setSelection(line_number, 0, line_number+1, 0)
self.editor.blockSignals(False)
if refresh and self.object_viewer is not None:
self.object_viewer.setSelection(0, line_number)
def getText(self):
return [l for l in self.editor.text().splitlines()]
def updateText(self, text, label="", fileSuffix="ngc"):
print("updating text")
if self.editingFlag: # don't update text if user is currently editing, to avoid propagation loops
return
# turn off signals to prevent event loops
self.editor.blockSignals(True)
if fileSuffix in self.suffixToLexer.keys():
self.__lexer = self.lexers[self.suffixToLexer[fileSuffix]]
self.editor.setLexer(self.__lexer)
#label+=" ("+self.suffixToLexer[fileSuffix]+")"
marginTextStyle= QsciStyle()
marginTextStyle.setPaper(QColor("#ffFF8888"))
self.editor.setText("")
self.label.setText(label)
skipped_lines = 0
annotation=None
self.editor.setText(text)
# for linenumber, l in enumerate(text):
# idx=linenumber-skipped_lines
# if l is None:
# #editor.append("\n")
# if annotation is None:
# annotation="<"
# else:
# annotation+="\n<"
# skipped_lines+=1
# self.editor.setMarginText(idx, "~", marginTextStyle)
# else:
# if annotation is not None:
# self.editor.annotate(idx-1, annotation, 0)
# annotation=None
# if '\0' in l or '\1' in l:
# self.editor.append(l.replace('\0+', '').replace('\0-', '').replace('\m', '').replace('\0^', '').replace('\1', ''))
# self.editor.markerAdd(idx, QsciScintilla.Circle)
# self.editor.setMarginText(idx, l[1], marginTextStyle)
# self.editor.fillIndicatorRange(idx, l.find('\0'), idx, l.rfind("\1"), 0)
# else:
# self.editor.append(l)
print("finished updating")
self.editor.blockSignals(False)
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,305 | codemakeshare/g-mint | refs/heads/master | /gcode.py | from numpy import *
from geometry import *
import traceback
class GCommand:
def __init__(self, command="", position=None, rotation=None, feedrate=None, rapid=False,
control_point=True, line_number=0,
axis_mapping = ["X", "Y", "Z"], axis_scaling = [1.0, 1.0, 1,0], rot_axis_mapping=["A", "B", "C"]):
self.command = command
self.axis_mapping = axis_mapping
self.axis_scaling = axis_scaling
self.rot_axis_mapping= rot_axis_mapping
self.control_point = control_point
self.feedrate = feedrate
self.rapid = rapid
self.position = position
self.rotation=rotation
self.line_number=line_number
self.interpolated=False
def to_output(self, current_pos = None, current_rotation = None):
return "%s" % (self.command)
def parse_line(self, input_line):
self.command = line
def interpolate_to_points(self, current_pos, current_rotation = None):
return []
class GPoint(GCommand):
def __init__(self, inside_model=True, control_point=False,
in_contact=True, interpolated = False, order=0, dist_from_model=None, **kwargs):
GCommand.__init__(self, **kwargs)
self.control_point = control_point
self.inside_model = inside_model
self.in_contact = in_contact
self.dist_from_model = dist_from_model
self.current_system_feedrate = None
self.interpolated=interpolated
self.order = order # indicates order of cascaded pocket paths - 0 is innermost (starting) path
self.gmode = "G1"
if self.rapid:
self.gmode = "G0"
def z_to_output(self):
if self.position is not None:
self.command = self.axis_mapping[2]+"%f " % (self.position[2])
if self.feedrate != None:
self.command = "%sF%f" % (self.command, self.feedrate)
return self.command
def to_output(self, current_pos = None, current_rotation = None):
am = self.axis_mapping
ram = self.rot_axis_mapping
self.command = ""
if not self.control_point:
for i in range(0, len(self.position)):
if current_pos is None or self.position[i]*self.axis_scaling[i] != current_pos[i]:
self.command += "%s%f " % (am[i], self.position[i]*self.axis_scaling[i])
if self.rotation is not None:
for i in range(0, len(self.rotation)):
if current_rotation is None or self.rotation[i] != current_rotation[i]:
self.command += "%s%f " % (ram[i], self.rotation[i])
# if self.feedrate!=None:
# self.command="%sF%f"%(self.command, self.feedrate)
return self.command
def interpolate_to_points(self, current_pos, current_rotation=None):
#interpolate 4th axis moves (for visualisation)
path = []
print("ITP", current_pos, current_rotation)
if current_rotation is not None and self.rotation is not None and current_rotation != self.rotation:
steps = int(dist(current_rotation, self.rotation) / 5.0)
if steps>1:
rot_stepsizes = [float(b - a)/float(steps) for (a,b) in zip(current_rotation, self.rotation)]
pos_stepsizes = [float(b - a) / float(steps) for (a, b) in zip(current_pos, self.position)]
for i in range(0, steps):
new_rotation = [ current_rotation[j] + i * rot_stepsizes[j] for j in range(0, len(current_rotation))]
new_pos = [ current_pos[j] + i * pos_stepsizes[j] for j in range(0, len(current_pos))]
path.append((GPoint(position=new_pos, rotation=new_rotation, feedrate=self.feedrate,
rapid=self.rapid, interpolated=True, line_number=self.line_number)))
path.append((GPoint(position=self.position, rotation = self.rotation, feedrate=self.feedrate, rapid=self.rapid, line_number=self.line_number)))
return path
class GArc(GPoint):
def __init__(self, ij=None, arcdir=None, control_point=False, **kwargs):
GPoint.__init__(self, **kwargs)
self.control_point = control_point
self.ij = ij
if arcdir is None:
print("Error: undefined arc direction!")
self.arcdir = arcdir
self.gmode = "G"+str(self.arcdir)
def z_to_output(self):
am = self.axis_mapping
if self.position is not None:
self.command = "%s%f " % (am[2], self.position[2])
if self.feedrate != None:
self.command = "%sF%f" % (self.command, self.feedrate)
return self.command
def to_output(self, current_pos = None, current_rotation = None, to_points=False):
am = self.axis_mapping
if not self.control_point:
self.command = "%s%f %s%f %s%f I%f J%f " % (am[0], self.position[0]*self.axis_scaling[0], am[1], self.position[1]*self.axis_scaling[1], am[2], self.position[2]*self.axis_scaling[2], self.ij[0], self.ij[1])
# if self.feedrate!=None:
# self.command="%sF%f"%(self.command, self.feedrate)
return self.command
def interpolate_to_points(self, current_pos, current_rotation = None):
arc_start = current_pos
path=[]
#print(arc_start, self.ij, self.position)
center = [arc_start[0] + self.ij[0], arc_start[1] + self.ij[1], self.position[2]]
start_angle = full_angle2d([arc_start[0] - center[0], arc_start[1] - center[1]], [1, 0])
end_angle = full_angle2d([self.position[0] - center[0], self.position[1] - center[1]], [1, 0])
angle_step = 0.05
angle = start_angle
radius = dist([center[0], center[1]], [arc_start[0], arc_start[1]])
radius2 = dist([center[0], center[1]], [self.position[0], self.position[1]])
if abs(radius-radius2)>0.01:
print("radius mismatch:", radius, radius2)
#interpolate arcs
if int(self.arcdir) == 3:
#print(int(self.arcdir))
while end_angle > start_angle:
end_angle -= 2.0 * PI
while angle > end_angle:
path.append(
GPoint(position=[center[0] + radius * cos(angle), center[1] - radius * sin(angle),
self.position[2]], feedrate=self.feedrate, rapid=self.rapid, interpolated=True, line_number=self.line_number));
angle -= angle_step
else:
while end_angle < start_angle:
end_angle += 2.0 * PI
while angle < end_angle:
path.append(
GPoint(position=[center[0] + radius * cos(angle), center[1] - radius * sin(angle), self.position[2]],
feedrate=self.feedrate, rapid=self.rapid, interpolated=True, line_number=self.line_number));
angle += angle_step
path.append(GPoint(position=self.position, feedrate=self.feedrate, rapid=self.rapid, line_number=self.line_number));
return path
class GCode:
def __init__(self, path=None):
self.default_feedrate = None
if path is None:
self.path = []
else:
self.path = path
self.default_feedrate = 1000
self.rapid_feedrate = 3000
self.initialisation = "G90G21G17G54\n"
self.laser_mode = False
self.laser_power = 1000
self.steppingAxis = 2 # major cutting axis for step-down (incremental cutting). Normally z-axis on mills.
def append_raw_coordinate(self, raw_point):
self.path.append(GPoint(raw_point))
def applyAxisMapping(self, axis_mapping):
for p in self.path:
p.axis_mapping = axis_mapping
def applyAxisScaling(self, axis_scaling):
for p in self.path:
p.axis_scaling = axis_scaling
def append(self, gpoint):
self.path.append(gpoint)
def combinePath(self, gcode):
if gcode is None or gcode.path is None:
return None
for p in gcode.path:
self.append(p)
def get_draw_path(self, start = 0, end=-1, start_rotation = [0,0,0], interpolate_arcs = True):
draw_path=[]
# current last position including interpolated points
current_pos = [0,0,0]
current_rotation = [0,0,0]
#last non-interpolated actual position
last_position = [0,0,0]
last_rotation = [0,0,0]
line=1
for p in self.path[start:end]:
if p.line_number==0:
p.line_number=line
line = max(p.line_number+1, line+1)
try:
point_list=[GPoint(position=p.position, feedrate=p.feedrate, rapid=p.rapid, line_number=p.line_number)]
if interpolate_arcs:
point_list = p.interpolate_to_points(last_position, last_rotation)
for ip in point_list:
if ip.position is None:
ip.position = current_pos
if ip.rotation is not None:
current_rotation = ip.rotation
else:
if current_rotation is not None:
ip.rotation = current_rotation
if ip.rotation is not None: # apply rotation to path points for preview only
ip.position = rotate_x(ip.position, ip.rotation[0] * PI / 180.0)
ip.position = rotate_y(ip.position, ip.rotation[1] * PI / 180.0)
ip.position = rotate_z(ip.position, ip.rotation[2] * PI / 180.0)
draw_path.append(ip)
except:
traceback.print_exc()
last_position = p.position
if p.rotation is not None:
last_rotation = p.rotation
if (len(draw_path)>1):
current_pos = draw_path[-1].position
if draw_path[-1].rotation is not None:
current_rotation = draw_path[-1].rotation
return draw_path
def get_end_points(self, start = 0, end=-1):
draw_path=[]
current_pos = [0,0,0]
for p in self.path[start:end]:
ip=p.interpolate_to_points(current_pos)
draw_path.append(ip[-1])
if (len(draw_path)>1):
current_pos = draw_path[-1].position
return draw_path
def getPathLength(self):
return len(self.path)
def appendPath(self, gcode):
self.append(GPoint(feedrate=gcode.default_feedrate, control_point=True))
for p in gcode.path:
self.append(p)
def estimate(self):
length = 0.0
duration = 0.0
rapid_length = 0.0
cut_length = 0.0
rapid_duration = 0.0
cut_duration = 0.0
current_feedrate = 1000
if self.default_feedrate != None:
current_feedrate = self.default_feedrate
paths = []
paths.append(self.path)
if len(paths) == 0 or len(paths[0]) == 0:
return (length, duration, current_feedrate, cut_length, rapid_length, cut_duration, rapid_duration)
lastp = None
for segment in paths:
for p in segment:
if p.feedrate is not None:
current_feedrate = p.feedrate
if p.feedrate is None and self.default_feedrate is not None and current_feedrate != self.default_feedrate:
current_feedrate = self.default_feedrate
if p.position is not None:
s_length = 0
if lastp is not None:
s_length = norm(array(p.position) - lastp)
lastp = array(p.position)
if p.rapid:
length += s_length
rapid_length += s_length
duration += s_length / self.rapid_feedrate
rapid_duration += s_length / self.rapid_feedrate
else:
length += s_length
cut_length += s_length
duration += s_length / current_feedrate
cut_duration += s_length / current_feedrate
# return "Path estimate: Length: %f mm; Duration: %f minutes. Last feedrate: %f"%(length, duration, current_feedrate)
return (length, duration, current_feedrate, cut_length, rapid_length, cut_duration, rapid_duration)
def toText(self, write_header=False, pure=False):
output = ""
#print("laser mode:", self.laser_mode, "pure: ", pure)
if not pure:
estimate = self.estimate()
if write_header:
print("Path estimate: Length: %f mm; Duration: %f minutes. Last feedrate: %f" % (estimate[0],
estimate[1], estimate[2]))
output += "( " + "Path estimate: Length: %f mm; Duration: %f minutes. Last feedrate: %f" % (
estimate[0], estimate[1], estimate[2]) + " )\n"
output += "G90G21G17G54\n"
if self.default_feedrate != None:
output += "G1F%f\n" % (self.default_feedrate)
complete_path = self.path
# if self.outpaths!=None and len(self.outpaths)>0:
# complete_path=[]
# for segment in self.outpaths:
# complete_path+=segment
rapid = None
current_feedrate = self.default_feedrate
current_pos = None
current_rotation = [0,0,0]
current_gmode = "G1"
for p in complete_path:
if isinstance(p, GPoint):
if p.rapid != rapid:
rapid = p.rapid
if rapid:
# in laser mode, issue a spindle off command before rapids
if self.laser_mode:
output += "M5\n"
# print "laser off"
output += "G0 "
else:
if self.laser_mode:
# in laser mode, issue a spindle on command after rapids
output += "M4 S%i\n"%(self.laser_power)
if p.gmode != current_gmode:
current_gmode = p.gmode
output += current_gmode+" "
else:
if p.gmode != current_gmode:
current_gmode = p.gmode
output += current_gmode+" "
output += "" + p.to_output(current_pos = current_pos, current_rotation = current_rotation)
if p.position is not None:
current_pos = p.position
if p.rotation is not None:
current_rotation = p.rotation
if p.feedrate is not None and (p.control_point or p.rapid == False and p.feedrate != current_feedrate):
current_feedrate = p.feedrate
if not p.control_point:
output += "F%f" % p.feedrate
#if p.feedrate is None and current_feedrate != self.default_feedrate:
# current_feedrate = self.default_feedrate
# output += "F%f" % current_feedrate
output += "\n"
if not pure:
output += "M02\n%\n"
return output
def write(self, filename):
f = open(filename, 'w')
f.write(self.toText(write_header=True))
f.close()
print(filename, "saved.")
known_commands = ["G", "F", "X", "Y", "Z", "M", "I", "J", "T", "A", "B", "C"]
def is_part_of_number(s):
return s == ' ' or s == "\t" or s == "-" or s == "+" or s == "." or (s >= "0" and s <= "9")
def parseline(line):
p = []
for i in range(0, len(line)):
if line[i] == '(':
break
for cmd in known_commands:
if line[i].upper().startswith(cmd):
# find end of number
j = i + len(cmd)
while j < len(line) and is_part_of_number(line[j]):
j += 1
value = line[i + len(cmd):j].strip()
p.append((cmd, value))
return p
#def write_coordinate(point, file):
# file.write("X%fY%fZ%f\n" % (point[0], point[1], point[2]))
def write_gcode(path, filename):
f = open(filename, 'w')
f.write("G90G21G17G54\n")
# go fast to starting point
f.write("G00")
file.write("Z%f\n" % (path[0][2]))
write_coordinate(path[0], f)
# linear interpolation, feedrate 800
f.write("G01F1500")
for p in path:
write_coordinate(p, f)
f.write("M02\n")
def read_gcode(filename):
try:
infile = open(filename)
except:
print("Can't open file:", filename)
return GCode()
datalines = infile.readlines();
return parse_gcode(datalines)
def parse_gcode(datalines):
x = 0
y = 0
z = 0
ra = 0
rb = 0
rc = 0
GCOM = ""
feed = None
rapid = False
arc = False
arcdir = None
path = GCode()
linecount = 0
for l in datalines:
i = 0
j = 0
k = 0
pl = parseline(l)
linecount += 1
# print linecount, pl
new_coord = False
new_rotation = False
try:
for c in pl:
if c[0].upper() == "X":
x = float(c[1]);
new_coord = True
if c[0].upper() == "Y":
y = float(c[1]);
new_coord = True
if c[0].upper() == "Z":
z = float(c[1]);
new_coord = True
if c[0].upper() == "A":
ra = float(c[1]);
new_coord = True
new_rotation = True
if c[0].upper() == "B":
rb = float(c[1]);
new_coord = True
new_rotation = True
if c[0].upper() == "C":
rc = float(c[1]);
new_coord = True
new_rotation = True
if c[0].upper() == "F":
feed = float(c[1])
if path.default_feedrate is None: # set the default feedrate to the first encountered feed
path.default_feedrate = feed
if c[0].upper() == "G" and (c[1] == "0" or c[1] == "00"):
rapid = True
arc = False
if c[0].upper() == "G" and (c[1] == "1" or c[1] == "01"):
rapid = False
arc = False
if c[0].upper() == "G" and (c[1] == "2" or c[1] == "3" or c[1] == "02" or c[1] == "03"): # arc interpolation
arc = True
arcdir = c[1]
rapid = False
if arc and c[0].upper() == "I":
i = float(c[1])
if arc and c[0].upper() == "J":
j = float(c[1])
except Exception as e:
print("conversion error in line %i:" % linecount, c)
print(e.message)
if new_coord:
if arc:
path.append(GArc(position=[x, y, z], ij= [i, j], arcdir = arcdir, feedrate=feed, rapid=rapid, command = l, line_number=linecount));
else:
if new_rotation:
path.append(GPoint(position=[x, y, z], rotation=[ra, rb, rc], feedrate=feed, rapid=rapid, command=l, line_number=linecount));
print("new rotation", ra, rb, rc)
else:
path.append(GPoint(position=[x, y, z], feedrate=feed, rapid=rapid, command = l, line_number=linecount));
else:
path.append(GCommand(command =l.strip(), feedrate = feed, line_number=linecount))
return path
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,306 | codemakeshare/g-mint | refs/heads/master | /tools/svgengrave.py | from guifw.abstractparameters import *
from geometry import *
from solids import *
import multiprocessing as mp
import time
import pyclipper
from polygons import *
from gcode import *
import svgparse
import xml.etree.ElementTree as ET
import re
from .milltask import SliceTask
class SVGEngraveTask(SliceTask):
def __init__(self, model=None, tools=[], viewUpdater=None, **kwargs):
SliceTask.__init__(self, **kwargs)
self.model=model.object
self.patterns=[]
self.path=None
# remap lathe axis for output. For Visualisation, we use x as long axis and y as cross axis. Output uses Z as long axis, x as cross.
#self.axis_mapping=["Z", "X", "Y"]
# scaling factors for output. We use factor -2.0 for x (diameter instead of radius), inverted from negative Y coordinate in viz
#self.axis_scaling = [1.0, -2.0, 0.0]
self.inputFile = FileParameter(parent=self, name="input file", fileSelectionPattern="SVG (*.svg)")
self.tool = ChoiceParameter(parent=self, name="Tool", choices=tools, value=tools[0])
self.operation = ChoiceParameter(parent=self, name="Operation", choices=["Slice", "Slice & Drop", "Outline", "Medial Lines"], value="Slice")
self.direction = ChoiceParameter(parent=self, name="Direction", choices=["inside out", "outside in"], value="inside out")
self.padding=NumericalParameter(parent=self, name="padding", value=0.0, step=0.1)
self.traverseHeight=NumericalParameter(parent=self, name='traverse height', value=self.model.maxv[2]+10, min=self.model.minv[2]-100, max=self.model.maxv[2]+100, step=1.0)
self.offset=NumericalParameter(parent=self, name='offset', value=0.0, min=-100, max=100, step=0.01)
self.waterlevel=NumericalParameter(parent=self, name='waterlevel', value=self.model.minv[2], min=self.model.minv[2], max=self.model.maxv[2], step=1.0)
self.minStep=NumericalParameter(parent=self, name="min. step size", value=0.1, min=0.0, max=50.0, step=0.01)
self.viewUpdater=viewUpdater
self.leftBound=NumericalParameter(parent=self, name="left boundary", value=self.model.minv[0], step=0.01)
self.rightBound=NumericalParameter(parent=self, name="right boundary", value=self.model.maxv[0], step=0.01)
self.innerBound=NumericalParameter(parent=self, name="inner boundary", value=0, step=0.01)
self.outerBound=NumericalParameter(parent=self, name="outer boundary", value=self.model.maxv[1], step=0.01)
self.toolSide=ChoiceParameter(parent=self, name="Tool side", choices=["external", "internal"], value = "external")
self.sideStep=NumericalParameter(parent=self, name="stepover", value=1.0, min=0.0001, step=0.01)
self.radialOffset = NumericalParameter(parent=self, name='radial offset', value=0.0, min=-100, max=100, step=0.01)
#self.diameter=NumericalParameter(parent=self, name="tool diameter", value=6.0, min=0.0, max=1000.0, step=0.1)
self.precision = NumericalParameter(parent=self, name='precision', value=0.005, min=0.001, max=1, step=0.001)
self.parameters = [self.inputFile, self.tool, [self.stockMinX, self.stockMinY], [self.stockSizeX, self.stockSizeY], self.operation, self.direction, self.toolSide, self.sideStep, self.traverseHeight,
self.radialOffset,
self.pathRounding, self.precision, self.sliceTop, self.sliceBottom, self.sliceStep, self.sliceIter, self.scalloping]
self.patterns = None
def generatePattern(self):
tree = ET.parse(self.inputFile.getValue())
root = tree.getroot()
ns = re.search(r'\{(.*)\}', root.tag).group(1)
self.patterns=[]
for geo in svgparse.getsvggeo(root):
print(geo.geom_type)
if geo.geom_type =="Polygon":
#convert shapely polygon to point list
points = [(x[0], -x[1], 0) for x in list(geo.exterior.coords)]
self.patterns.append(points)
for hole in geo.interiors:
points = [(x[0], -x[1], 0) for x in list(hole.coords)]
self.patterns.append(points)
if geo.geom_type =="MultiPolygon":
for poly in geo:
#convert shapely polygon to point list
points = [(x[0], -x[1], 0) for x in list(poly.exterior.coords)]
self.patterns.append(points)
self.model_minv, self.model_maxv = polygon_bounding_box([p for pattern in self.patterns for p in pattern ])
self.stockMinX.updateValue(self.model_minv[0])
self.stockMinY.updateValue(self.model_minv[1])
self.stockSizeX.updateValue(self.model_maxv[0] - self.model_minv[0])
self.stockSizeY.updateValue(self.model_maxv[1] - self.model_minv[1])
print(self.patterns)
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,307 | codemakeshare/g-mint | refs/heads/master | /tools/cameraviewer.py | from OrthoGLViewWidget import *
from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import numpy as np
import cv2
from threading import Thread
class CameraViewer(QtGui.QWidget, Thread):
changePixmap = pyqtSignal(QImage)
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent=parent)
self.cap=None
self.image_label = QLabel("waiting for video...")
self.image_label.move(0, 0)
self.image_label.resize(500, 300)
self.image_label.setScaledContents(True)
self.scroll = QtGui.QScrollArea(self)
self.scroll.setWidget(self.image_label)
self.main_layout = QVBoxLayout()
self.main_layout.addWidget(self.scroll)
self.setLayout(self.main_layout)
self.zoomSlider = QSlider(orientation=QtCore.Qt.Horizontal)
self.zoomSlider.setMinimum(100)
self.zoomSlider.setMaximum(200)
self.main_layout.addWidget(self.zoomSlider)
self.busy = False
#self.read_timer = QtCore.QTimer()
#self.read_timer.setInterval(100)
#self.read_timer.timeout.connect(self.updateCamera)
#self.read_timer.start()
self.setVisible(False)
self.active=True
self.imagesize = [300,200]
@pyqtSlot(QImage)
def setImage(self, image):
self.image_label.setPixmap(QPixmap.fromImage(image))
def resizeEvent(self, event):
self.imagewidth = self.scroll.frameGeometry().width()-2
def updateCamera(self):
if self.isVisible():
if not self.busy and self.cap is not None and self.cap.isOpened():
busy = True
ret, frame = self.cap.read()
if ret == True:
if self.zoomSlider.value() > 100:
frame = self.Zoom(frame, self.zoomSlider.value() / 100.0)
rgbImage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
h, w, ch = rgbImage.shape
bytesPerLine = ch * w
convertToQtFormat = QtGui.QImage(rgbImage.data, w, h, bytesPerLine, QtGui.QImage.Format_RGB888)
p = convertToQtFormat.scaled(self.imagewidth, self.imagewidth*h/w, Qt.KeepAspectRatio)
#self.changePixmap.emit(p)
self.image_label.resize(self.imagewidth, self.imagewidth*h/w)
self.image_label.setPixmap(QPixmap.fromImage(p))
self.busy = False
cv2.waitKey(10)
else:
try:
self.cap = cv2.VideoCapture(0)
self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280);
self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720);
self.busy = False
except:
print("problem setting up camera")
else:
if self.cap is not None:
self.cap.release()
self.cap = None
def Zoom(self, cv2Object, zoomSize):
old_size = (cv2Object.shape[0]/zoomSize, cv2Object.shape[1]/zoomSize)
new_size = (int(zoomSize * cv2Object.shape[1]), int(zoomSize * cv2Object.shape[0]))
#cv2Object = cv2.resize(cv2Object, new_size)
center = (cv2Object.shape[0] / 2, cv2Object.shape[1] / 2)
cv2Object = cv2Object[int(center[0]-(old_size[0]/2)):int((center[0] +(old_size[0]/2))), int(center[1]-(old_size[1]/2)):int(center[1] + (old_size[0]/2))]
return cv2Object
def run(self):
print("starting update thread")
while self.active:
self.updateCamera()
def stop(self):
self.active=False | {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,308 | codemakeshare/g-mint | refs/heads/master | /taskdialog.py |
from collections import OrderedDict
from tools.modeltool import *
from tools.milltask import *
from tools.pathtool import *
from tools.threading_tool import *
from tools.boring_tool import *
from tools.timing_pulley import *
from tools.lathetask import *
from tools.lathethreadingtool import *
from tools.svgengrave import *
from tools.textengrave import *
import traceback
from guifw.gui_elements import *
import json
class TaskDialog(QtWidgets.QWidget):
def __init__(self, modelmanager, tools, path_output):
QtWidgets.QWidget.__init__(self)
self.path_output = path_output
self.modelmanager = modelmanager
self.tools = tools
self.layout = QtWidgets.QGridLayout()
self.setLayout(self.layout)
self.availableTasks = OrderedDict([("Slice", SliceTask),
("Pattern", PatternTask),
("lathe tool", LatheTask),
("lathe threading", LatheThreadingTool),
("Boring", BoringTool),
("Threading", ThreadingTool),
("timing pulley",TimingPulleyTool),
("SVG engrave", SVGEngraveTask),
("Text engrave", TextEngraveTask)]
)
self.tasktab = ListWidget(itemlist=[], title="Milling tasks", itemclass=self.availableTasks, name="Task",
tools=tools, model=modelmanager, on_select_cb=self.display_pattern, viewUpdater=self.modelmanager.viewer.showPath)
self.layout.addWidget(self.tasktab, 0, 0, 1, 2)
create_pattern_btn = QtWidgets.QPushButton("generate pattern")
start_one_btn = QtWidgets.QPushButton("start selected")
start_all_btn = QtWidgets.QPushButton("start all")
#save_btn = QtWidgets.QPushButton("save")
#save_btn.clicked.connect(self.saveTasks)
#load_btn = QtWidgets.QPushButton("load")
#load_btn.clicked.connect(self.loadTasks)
self.layout.addWidget(create_pattern_btn, 1, 1)
self.layout.addWidget(start_one_btn, 2, 0)
self.layout.addWidget(start_all_btn, 2, 1)
#self.layout.addWidget(save_btn, 3, 0)
#self.layout.addWidget(load_btn, 3, 1)
create_pattern_btn.clicked.connect(self.generatePattern)
start_one_btn.clicked.connect(self.startSelectedTask)
self.lastFilename = None
def display_pattern(self, selectedTool):
pattern = []
if selectedTool.patterns != None:
pattern = selectedTool.patterns
# for pat in selectedTool.patterns:
# pattern+=pat
self.modelmanager.viewer.showPath(pattern)
def generatePattern(self):
try:
self.tasktab.selectedTool.generatePattern()
pattern = self.tasktab.selectedTool.patterns
# for pat in self.tasktab.selectedTool.patterns:
# pattern+=pat
self.modelmanager.viewer.showPath(pattern)
except Exception as e:
print(e)
traceback.print_exc()
def updateView(self, newPath, tool=None):
self.modelmanager.viewer.showPath(newPath, tool)
def startSelectedTask(self):
try:
newPath = self.tasktab.selectedTool.calcPath()
existingPath = self.path_output.pathtab.findItem(self.tasktab.selectedTool.name.value)
if existingPath is None:
self.path_output.pathtab.listmodel.addItem(
PathTool(name=self.tasktab.selectedTool.name.value, path=newPath, model=self.tasktab.selectedTool.model,
viewUpdater=self.path_output.view_updater, tool=self.tasktab.selectedTool.tool.getValue(),
source=self.tasktab.selectedTool))
else:
# update path
existingPath.updatePath(newPath)
self.updateView(newPath)
except Exception as e:
print(e)
traceback.print_exc()
def saveTasks(self):
filename, pattern = QtWidgets.QFileDialog.getSaveFileName(self, 'Save file', '', "*.json")
if len(filename)==0:
return
print("saving File:", filename)
items = self.tasktab.getItems()
exportedItems = [i.toDict() for i in items]
print(exportedItems)
jdata = json.dumps(exportedItems)
with open(filename, "w") as file:
file.write(jdata)
def loadTasks(self):
filename, pattern = QtWidgets.QFileDialog.getOpenFileName(self, 'Open file', '', "*.json")
if len(filename)==0:
return
data = None
with open(filename) as file:
data = file.read()
importedData = json.loads(data)
classDict = {}
for name, c in self.availableTasks.items():
print(name, str(c.__name__), c)
classDict[str(c.__name__)] = c
for i in importedData:
item = buildItemFromDict(i, classDict) (name = i["name"], tools = self.tools, model = self.modelmanager)
item.restoreParametersFromDict(i["parameters"])
print(item)
self.tasktab.listmodel.addItem(item)
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,309 | codemakeshare/g-mint | refs/heads/master | /mint.py | from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtWidgets import *
from tools import *
#from tools.modeltool import *
#from tools.tool import *
#from tools.milltask import *
#import pyqtgraph.opengl as gl
#import pyqtgraph as pg
from solids import *
import sys
from guifw.gui_elements import *
#from modeldialog import *
from pathdialog import *
from taskdialog import *
from grbldialog import *
from objectviewer import *
from gcode_editor import *
class CAMGui(QtGui.QSplitter):
def __init__(self):
QtGui.QSplitter.__init__(self)
self.editor = GcodeEditorWidget()
self.objectviewer = ObjectViewer(editor=self.editor)
#self.objectviewer = ObjectViewer()
self.tabs=QtGui.QTabWidget()
self.availablePathTools = OrderedDict([("Load GCode", PathTool), ("Thread milling", threading_tool.ThreadingTool)])
self.pathtab = PathDialog(viewer = self.objectviewer, tools=None, editor=self.editor, availablePathTools = self.availablePathTools)
self.grbltab = GrblDialog(path_dialog=self.pathtab, editor=self.editor)
#self.tabs.addTab(self.pathtab, "Path tools")
#self.tabs.addTab(self.grbltab, "Machine")
self.addWidget(self.grbltab)
self.centerWidget = QtGui.QSplitter(Qt.Vertical)
self.centerWidget.addWidget(self.objectviewer)
self.centerWidget.addWidget(self.editor)
self.addWidget(self.centerWidget)
#self.addWidget(self.pathtab)
self.setWindowTitle('Machine Interface')
self.updateGeometry()
self.resize(1200, 600)
## Display the widget as a new window
app = QtGui.QApplication([])
camgui=CAMGui()
camgui.show()
if len(sys.argv)>1 and sys.argv[1]=="-f":
camgui.showFullScreen()
## Start the Qt event loop
app.exec_()
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,310 | codemakeshare/g-mint | refs/heads/master | /tengrave.py | from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtWidgets import *
from tools import *
#from tools.modeltool import *
#from tools.tool import *
#from tools.milltask import *
#import pyqtgraph.opengl as gl
#import pyqtgraph as pg
from solids import *
import sys
from guifw.gui_elements import *
#from modeldialog import *
from pathdialog import *
from taskdialog import *
from grbldialog import *
from objectviewer import *
from gcode_editor import *
from tools.textengrave import *
from tools.tool import *
from guifw.abstractparameters import *
import tools.modeltool
class SimpleEngrave(TextEngraveTask):
def __init__(self, viewUpdater = None, model = None, pathdialog = None, **kwargs):
self.laser_tool = Tool(name="Laser", diameter=0.1)
self.path_dialog = pathdialog
TextEngraveTask.__init__(self, model = model, tools = [self.laser_tool], viewUpdater = viewUpdater)
self.output_pathtool = PathTool(name="text_path", path=self.path, model=self.model,
viewUpdater=self.updateOutputView, tool=self.laser_tool,
source=None)
self.output_pathtool.feedrate.updateValue(900)
self.textInput.callback = self.create_path
self.fontsize.updateValue(13)
self.radialOffset.updateValue(0.05)
self.create = ActionParameter(parent = self, name = "create path", callback = self.create_path)
self.parameters = [[self.textInput, self.create],
[self.font, self.fontsize],
[self.output_pathtool.laser_mode,
self.output_pathtool.feedrate],
self.tool,
self.traverseHeight,
self.radialOffset,
]
def updateOutputView(self, path, tool):
self.path_dialog.update_view(path=self.output_pathtool.getCompletePath(), tool=self.laser_tool)
def create_path(self, param):
self.generatePattern()
self.path = self.calcPath()
self.viewUpdater(self.path)
existingPath = self.path_dialog.pathtab.findItem("text_path")
if existingPath is None:
self.path_dialog.pathtab.listmodel.addItem(self.output_pathtool)
else:
# update path
existingPath.updatePath(self.path)
class CAMGui(QtWidgets.QSplitter):
def __init__(self):
QtWidgets.QSplitter.__init__(self)
self.editor = GcodeEditorWidget()
self.objectviewer = ObjectViewer(editor=self.editor)
#self.objectviewer = ObjectViewer()
self.tabs=QtWidgets.QTabWidget()
self.modeltool = tools.modeltool.ModelTool(viewUpdater=self.objectviewer.showPath)
self.availablePathTools = OrderedDict([("Load GCode", PathTool)])
self.pathtab = PathDialog(viewer = self.objectviewer, tools=None, editor=self.editor, availablePathTools = self.availablePathTools)
self.grbltab = GrblDialog(path_dialog=self.pathtab, editor=self.editor)
self.engrave_tool = SimpleEngrave(viewUpdater = self.objectviewer.showPath, model = self.modeltool, pathdialog = self.pathtab )
self.engrave_tab = ToolPropertyWidget(parent = self, tool = self.engrave_tool)
self.left_widget = QtWidgets.QSplitter(Qt.Vertical)
#self.left_layout = QtWidgets.QVBoxLayout()
self.left_widget.addWidget(self.grbltab)
self.left_widget.addWidget(self.engrave_tab)
self.addWidget(self.left_widget)
self.centerWidget = QtWidgets.QSplitter(Qt.Vertical)
self.centerWidget.addWidget(self.objectviewer)
self.centerWidget.addWidget(self.editor)
self.addWidget(self.centerWidget)
self.setWindowTitle('Machine Interface')
self.updateGeometry()
self.resize(1600, 1200)
## Display the widget as a new window
app = QtWidgets.QApplication([])
camgui=CAMGui()
camgui.show()
if len(sys.argv)>1 and sys.argv[1]=="-f":
camgui.showFullScreen()
## Start the Qt event loop
app.exec_()
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,311 | codemakeshare/g-mint | refs/heads/master | /tools/tool_lathe_insert.py | import math
from guifw.abstractparameters import *
import polygons
class Tool_lathe_insert(ItemWithParameters):
def __init__(self, name=None, length = 10, width = 3, angle = 90, corner_radius = 0, shape='prismatic', viewer = None, **kwargs):
ItemWithParameters.__init__(self, **kwargs)
if name==None:
self.name=TextParameter(parent=self, name="Description", value="%s cutter - %smm"%(shape, width))
else:
self.name=TextParameter(parent=self, name="Description", value=name)
self.viewer = viewer
self.shape = ChoiceParameter(parent=self, name="Cutter shape", choices=['prismatic', 'round'], value=shape, callback = self.previewTool)
self.length = NumericalParameter(parent=self, name="length", value=length, min=0.0, step=0.1, callback = self.previewTool)
self.width = NumericalParameter(parent=self, name="width", value=width, min=0.0, step=0.1, callback = self.previewTool)
self.lateral_offset = NumericalParameter(parent=self, name="lateral offset", value=0.0, step=0.1, callback = self.previewTool)
self.rotation = NumericalParameter(parent=self, name="rotation", value=0, min=-180, max = 180, step=1, callback = self.previewTool)
self.includedAngle = NumericalParameter(parent=self, name="included angle", value=angle, min=0.0, max = 90, step=1.0, callback = self.previewTool)
self.cornerRadius = NumericalParameter(parent=self, name="corner radius", value=corner_radius, min=0.0, step=0.1, callback = self.previewTool)
self.chipload =NumericalParameter(parent=self, name='chipload (mm/tooth)', value=0.03, min=0.01, max=1, step=0.001)
self.engagement = NumericalParameter(parent=self, name='max. engagement/WOC', value=0.5, min=0.1, max=30, step=0.1)
self.maxDOC = NumericalParameter(parent=self, name='max. depth of cut (DOC)', value=10.0, min=0.0, max=100, step=0.1)
self.surfacespeed=NumericalParameter(parent=self, name='surface speed (m/min)', value=60, min=1, max=600, step=10)
self.spindleRPM=NumericalParameter(parent=self, name='spindle speed (RPM)', value=0, min=1, max=100000, step=1, editable=False)
self.feedrate=NumericalParameter(parent=self, name='feedrate(mm/min)', value=100, min=1, max=20000, step=1, editable=False)
self.specificCuttingForce=NumericalParameter(parent=self, name='spec. cutting force (N/mm^2)', value=700.0, min=0.0, max=20000.0, step=100.0, editable=True)
self.mrr =NumericalParameter(parent=self, name='MRR (cm^3/min)', value=0.0, min=0, max=20000, step=1, editable=False)
self.cuttingForce =NumericalParameter(parent=self, name='cutting force', value=0, min=0, max=20000, step=1, editable=False)
self.spindleLoad =NumericalParameter(parent=self, name='spindle load (Watt)', value=0, min=0, max=20000, step=1, editable=False)
self.parameters=[self.name, self.shape, self.length, self.width, self.rotation, self.includedAngle, self.cornerRadius, self.lateral_offset,
self.chipload, self.engagement, self.maxDOC,
self.surfacespeed,
self.spindleRPM,
self.feedrate,
self.specificCuttingForce, self.mrr, self.cuttingForce, self.spindleLoad]
def getType(self):
return "lathe"
def getDescription(self):
return "%s insert %i deg - %s mm"%(self.shape.getValue(), self.includedAngle.getValue(), self.width.getValue())
def previewTool(self, value):
if self.viewer is not None:
poly = self.toolPoly()
poly.append(poly[0])
self.viewer.showPath([poly])
def toolPoly(self, side="external"):
tool_poly = None
la = self.rotation.getValue()
ia = self.includedAngle.getValue() + la
w = self.width.getValue()
l = self.length.getValue()
v1 = [math.sin(la*math.pi/180.0) * l, -math.cos(la*math.pi/180.0) * l]
v2 = [math.sin(ia*math.pi/180.0) * w, -math.cos(ia*math.pi/180.0) * w]
lo = self.lateral_offset.getValue()
tool_poly = [[0, 0], v1, [v1[0]+v2[0], v1[1]+v2[1]], v2]
# shift by lateral offset
tool_poly = [[p[0]+lo, p[1]] for p in tool_poly]
cr = min([self.cornerRadius.getValue(), w/2.0-0.01, l/2.0-0.01])
if cr>0:
offPoly = polygons.PolygonGroup(polys=[tool_poly], precision=0.001)
roundPoly = offPoly.offset(radius=cr)
roundPoly = roundPoly.offset(radius=-cr)
tool_poly = roundPoly.polygons[0]
bb = roundPoly.getBoundingBox()
shift_x = 0
shift_y = 0
if max([p[0] for p in bb]) < 0: # whole insert on right side
shift_x = -max([p[0] for p in bb])
if min([p[0] for p in bb]) > 0: # whole insert on left side
shift_x = -min([p[0] for p in bb])
if max([p[1] for p in bb]) < 0: # whole insert on external side
shift_y = -max([p[1] for p in bb])
if min([p[1] for p in bb]) > 0: # whole insert on internal side
shift_y = -min([p[1] for p in bb])
roundPoly.translate([shift_x, shift_y, 0])
return tool_poly
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,312 | codemakeshare/g-mint | refs/heads/master | /objectviewer2D.py | from OrthoGLViewWidget import *
from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtWidgets import *
import pyqtgraph.opengl as gl
import pyqtgraph as pg
from tools import *
from solids import *
class ObjectViewer2D(QtGui.QWidget):
def __init__(self, parent=None, editor=None):
QtGui.QWidget.__init__(self, parent=parent)
self.busy = False
## Create a GL View widget to display data
self.visual_divider = 1
self.pathPlot = None
self.stats = None
self.editor=editor
self.gm = None
self.layout = QtGui.QVBoxLayout()
self.setLayout(self.layout)
self.w = pg.PlotWidget(name='Plot1')
self.w.setAspectLocked(True)
# self.w.show()
self.layout.addWidget(self.w)
self.setWindowTitle('CAM preview')
self.stats = QtGui.QLabel(parent=self)
self.stats.setMaximumHeight(20)
self.layout.addWidget(self.stats)
self.path_slider = QtGui.QSlider(parent=self)
self.path_slider.setOrientation(QtCore.Qt.Horizontal)
self.layout.addWidget(self.path_slider)
self.path_slider.valueChanged.connect(self.updatePathPlot)
# self.show()
self.layout.setSpacing(0)
#self.layout.setMargin(0)
self.resize(800, 600)
# g = gl.GLGridItem()
# g.scale(2,2,1)
# g.setDepthValue(10) # draw grid after surfaces since they may be translucent
# self.w.addItem(g)
self.rawpath = []
self.linecolors = []
self.pointcolors = []
self.gl_cutting_tool = None
def showFacets(self, object):
pass
def showHeightMap(self, object, visual_divider=4):
pass
def showHeightMap2(self, object):
pass
def showPath(self, path, color=(1.0, 1.0, 1.0, 1.0), width=1, tool = None):
print("showPath", tool)
rawpath = path
self.gpoints = None
if path.__class__.__name__ == "GCode":
self.rawpath = []
self.linecolors = []
self.pointcolors = []
self.gpoints = path
self.interpolated = path.get_draw_path(interpolate_arcs=True)
colorcycle = 0.0
# if path.outpaths!=None and len(path.outpaths)>0:
# point_count = sum([len(subpath) for subpath in path.outpaths ])
# for subpath in path.outpaths:
# for p in subpath:
# if p.position is not None:
# self.rawpath.append(p.position)
# point_color=(1.0-(colorcycle/point_count), (colorcycle/point_count), 0.0, 1.0)
# if p.rapid:
# point_color=(1.0, 1.0, 1.0, 1.0)
# if not p.inside_model:
# point_color=(0.0, 0.0, 1.0, 1.0)
# if not p.in_contact:
# point_color=(0.3, 0.3, 0.7, 0.5)
# self.colors.append(point_color)
# colorcycle+=1
# else:
point_count = len(path.path)
for p in path.get_draw_path():
if p.position is not None:
self.rawpath.append(p.position)
point_color = (1.0 - (colorcycle / point_count), (colorcycle / point_count), 0.0, 1.0)
if p.rapid:
point_color = (1.0, 1.0, 1.0, 1.0)
if not p.inside_model:
point_color = (0.0, 0.0, 1.0, 1.0)
if not p.in_contact:
point_color = (0.3, 0.3, 0.7, 0.5)
self.linecolors.append(point_color)
if not p.interpolated:
self.pointcolors.append(point_color)
else:
self.pointcolors.append((0.0,0.0,0.0,0.0))
colorcycle += 1
else:
self.rawpath = []
self.colors = []
for p in path:
# rawpath.append(p[0])
# colors.append((0.5, 0.5, 0.5, 0.5))
self.rawpath += p
self.linecolors += [(float(i) / len(p), float(i) / len(p), float(i) / len(p), 1.0) for i in
range(0, len(p))]
self.rawpath.append(p[-1])
self.pointcolors.append((0.1, 0.1, 0.1, 0.2))
# colors=[color for p in rawpath]
if len(self.rawpath) == 0: return
self.path_slider.setMaximum(len(self.rawpath))
self.path_slider.setValue(len(self.rawpath))
self.updatePathPlot(width)
drawpath = self.rawpath
xpath, ypath, zpath = zip(*drawpath)
print(array(drawpath))
if self.pathPlot == None:
print("plotting new path in 2D")
self.color = QtGui.QColor(128, 128, 128)
self.pathPlot = self.w.plot(pen=pg.mkPen(self.color), x=array(xpath), y=array(ypath), color=array(self.pointcolors))
self.pathPlotHighlight = self.w.scatterPlot(pen=pg.mkPen(self.color), x=array(xpath), y=array(ypath), color=array(self.pointcolors), size=3.0)
self.w.addItem(self.pathPlot)
self.w.addItem(self.pathPlotHighlight)
else:
print("updating path plot")
self.pathPlot.setData(x=array(xpath), y=array(ypath), color=array(self.linecolors))
self.pathPlotHighlight.setData(x=array(xpath), y=array(ypath), color=array(self.pointcolors))
def setSelection(self, start_index, end_index):
self.path_slider.blockSignals(True)
self.path_slider.setValue(end_index)
self.path_slider.blockSignals(False)
end_index = self.path_slider.value()
if end_index == 0:
return
if start_index>=end_index:
return
drawpath = self.rawpath[start_index:end_index]
if self.pathPlot is not None:
self.pathPlot.setData(pos=array(drawpath), color=array(self.linecolors[start_index:end_index]))
self.pathPlotHighlight.setData(pos=array(drawpath), color=array(self.pointcolors[start_index:end_index]))
if self.gpoints is not None and len(self.gpoints.path)>end_index-1:
lp = self.gpoints.path[end_index - 1]
feed = self.gpoints.default_feedrate
if lp.feedrate is not None:
feed = lp.feedrate
if lp.feedrate is not None and lp.position is not None:
self.stats.setText("x=% 4.2f y=% 4.2f z=% 4.2f f=%i, line=%i" % (lp.position[0], lp.position[1], lp.position[2], int(feed), lp.line_number))
def updatePathPlot(self, width=0.1, updateEditor=True):
end_index = self.path_slider.value()
if updateEditor and self.editor is not None:
self.editor.highlightLine(end_index)
if end_index == 0:
return
drawpath = self.rawpath[0:end_index]
if self.pathPlot is not None:
self.pathPlot.setData(pos=array(drawpath), color=array(self.linecolors[0:end_index]))
self.pathPlotHighlight.setData(pos=array(drawpath), color=array(self.pointcolors[0:end_index]))
if self.gpoints is not None:
lp = self.interpolated[end_index - 1]
feed = self.gpoints.default_feedrate
if lp.feedrate is not None:
feed = lp.feedrate
if lp.feedrate is not None and lp.position is not None:
self.stats.setText(
"x=% 4.2f y=% 4.2f z=% 4.2f f=%i, line=%i" % (lp.position[0], lp.position[1], lp.position[2], int(feed), lp.line_number))
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,313 | codemakeshare/g-mint | refs/heads/master | /tools/modeltool.py | from guifw.abstractparameters import *
class ModelTool(ItemWithParameters):
def __init__(self, object=None, viewUpdater=None, **kwargs):
ItemWithParameters.__init__(self, **kwargs)
self.object=object
self.viewUpdater=viewUpdater
self.rotateX=ActionParameter(parent=self, name='rotate X', callback=self.rotate_x)
self.rotateY=ActionParameter(parent=self, name='rotate Y', callback=self.rotate_y)
self.rotateZ=ActionParameter(parent=self, name='rotate Z', callback=self.rotate_z)
self.scaleX=NumericalParameter(parent=self, name="scale X", value=1.0, step=0.1, enforceRange=False, enforceStep=False)
self.scaleY=NumericalParameter(parent=self, name="Y", value=1.0, step=0.1, enforceRange=False, enforceStep=False)
self.scaleZ=NumericalParameter(parent=self, name="Z", value=1.0, step=0.1, enforceRange=False, enforceStep=False)
self.scale=ActionParameter(parent=self, name='scale', callback=self.scale)
self.collapseTop=ActionParameter(parent=self, name='Collapse to Top', callback=self.collapseTop)
self.collapseBottom=ActionParameter(parent=self, name='Collapse to Bottom', callback=self.collapseBottom)
self.heightMapResolution=NumericalParameter(parent=self, name="Height map resolution", value=1.0, step=0.1, enforceRange=False, enforceStep=False)
self.heightMapButtonTop=ActionParameter(parent=self, name='Calculate Heightmap (top)', callback=self.heightmapTop)
self.heightMapButtonBottom=ActionParameter(parent=self, name='Calculate Heightmap (bottom)', callback=self.heightmapBottom)
self.parameters=[[self.rotateX, self.rotateY, self.rotateZ],
self.scaleX, self.scaleY, self.scaleZ, self.scale,
[self.collapseTop, self.collapseBottom],
self.heightMapResolution,
self.heightMapButtonTop,
self.heightMapButtonBottom]
def rotate_x(self):
if self.object!=None:
self.object.rotate_x()
if self.viewUpdater!=None:
self.viewUpdater()
def rotate_y(self):
if self.object!=None:
self.object.rotate_y()
if self.viewUpdater!=None:
self.viewUpdater()
def rotate_z(self):
if self.object!=None:
self.object.rotate_z()
if self.viewUpdater!=None:
self.viewUpdater()
def scale(self):
if self.object!=None:
self.object.scale([self.scaleX.getValue(), self.scaleY.getValue(), self.scaleZ.getValue()])
if self.viewUpdater!=None:
self.viewUpdater()
def collapseTop(self):
if self.object!=None:
self.object.collapse_to_surface(False)
if self.viewUpdater!=None:
self.viewUpdater()
def collapseBottom(self):
if self.object!=None:
self.object.collapse_to_surface(True)
if self.viewUpdater!=None:
self.viewUpdater()
def heightmapTop(self):
if self.object!=None:
self.object.calc_height_map_scanning(grid=self.heightMapResolution.getValue(), waterlevel="max" )
#self.object.interpolate_gaps(self.object.maxv[2])
if self.viewUpdater!=None:
self.viewUpdater(mode="heightmap")
def heightmapBottom(self):
if self.object!=None:
self.object.calc_height_map_scanning(grid=self.heightMapResolution.getValue(), waterlevel="min" )
#self.object.interpolate_gaps(self.object.minv[2])
if self.viewUpdater!=None:
self.viewUpdater(mode="heightmap")
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,314 | codemakeshare/g-mint | refs/heads/master | /lint.py | from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtWidgets import *
from tools import *
from tools.modeltool import *
from tools.tool import *
from tools import cameraviewer
from tools import lathethreadingtool
from tools.milltask import *
#import pyqtgraph.opengl as gl
#import pyqtgraph as pg
from solids import *
import sys
from guifw.gui_elements import *
from modeldialog import *
from pathdialog import *
from taskdialog import *
from grbldialog import *
from objectviewer import *
from gcode_editor import *
class CAMGui(QtGui.QSplitter):
def __init__(self):
QtGui.QSplitter.__init__(self)
self.tabs=QtGui.QTabWidget()
self.availablePathTools = OrderedDict([("Load GCode", PathTool), ("Lathe threading", LatheThreadingTool)])
self.editor = GcodeEditorWidget()
#self.objectviewer = ObjectViewer(editor=self.editor)
#self.objectviewer.w.opts["tilt"]=-90.0
self.objectviewer = None
self.editor.object_viewer = self.objectviewer
self.pathtab = PathDialog(viewer = self.objectviewer, tools=None, editor=self.editor, availablePathTools = self.availablePathTools)
self.grbltab = GrblDialog(path_dialog=self.pathtab, machine="lathe", editor=self.editor)
self.centerWidget = QtGui.QSplitter(Qt.Vertical)
#self.tabs.addTab(self.pathtab, "Path tools")
#self.tabs.addTab(self.grbltab, "Machine")
self.addWidget(self.grbltab)
self.tabs.addTab(self.editor, "GCode")
self.camera = cameraviewer.CameraViewer()
self.camera.start()
self.tabs.addTab(self.camera, "Camera")
#self.centerWidget.addWidget(self.objectviewer)
#self.centerWidget.addWidget(self.editor)
self.centerWidget.addWidget(self.tabs)
self.centerWidget.setSizes([4000,4000])
self.addWidget(self.centerWidget)
#self.addWidget(self.pathtab)
self.tabs.addTab(self.pathtab, "Paths")
self.setSizes([100, 1200, 300])
self.setWindowTitle('Machine Interface')
self.updateGeometry()
self.resize(1200, 600)
## Display the widget as a new window
app = QtGui.QApplication([])
camgui=CAMGui()
camgui.show()
if len(sys.argv)>1 and sys.argv[1]=="-f":
camgui.showFullScreen()
## Start the Qt event loop
app.exec_()
camgui.camera.stop()
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,315 | codemakeshare/g-mint | refs/heads/master | /tools/timing_pulley.py | from guifw.abstractparameters import *
from gcode import *
class TimingPulleyTool(ItemWithParameters):
def __init__(self, path=[], model=None, tools=[], viewUpdater=None, **kwargs):
ItemWithParameters.__init__(self, **kwargs)
self.model = None #threading tool doesn't have a model
self.viewUpdater = viewUpdater
self.path = GCode()
self.patterns=None
self.tool=ChoiceParameter(parent=self, name="Tool", choices=tools, value=tools[0])
self.pitch=NumericalParameter(parent=self, name='pitch', value=2, enforceRange=False, step=0.1, callback = self.generatePath)
self.tooth_width = NumericalParameter(parent=self, name='tooth width', value=1.1, enforceRange=False, step=0.01, callback = self.generatePath)
self.tooth_depth_offset = NumericalParameter(parent=self, name='tooth depth offset', value=0.25, enforceRange=False, step=0.01, callback = self.generatePath)
self.tooth_flank_factor = NumericalParameter(parent=self, name='tooth flank factor', value=1.5, enforceRange=False, step=0.1, callback = self.generatePath)
self.chamfering_depth = NumericalParameter(parent=self, name='chamfer', value=0.0, enforceRange=False, step=0.01, callback=self.generatePath)
self.teeth=NumericalParameter(parent=self, name='teeth', value=40, enforceRange=False, step=1, callback = self.generatePath)
self.width=NumericalParameter(parent=self, name='width', value=10, enforceRange=False, step=1, callback = self.generatePath)
self.stepDepth=NumericalParameter(parent=self, name='max. stepdown', value=1, min = 0.05, max=20, enforceRange=True, step=0.1, callback = self.generatePath)
self.traverseHeight=NumericalParameter(parent=self, name='traverse height', value=5.0, enforceRange=False, step=1.0, callback = self.generatePath)
self.parameters=[self.tool, self.pitch, self.teeth, self.width, self.tooth_width, self.tooth_depth_offset, self.tooth_flank_factor, self.chamfering_depth, self.stepDepth, self.traverseHeight]
self.generatePath(None)
def generatePath(self, parameter):
self.path.outpaths=[]
path = []
self.path.path=[]
pitch = self.pitch.getValue()
teeth = self.teeth.getValue()
tooth_depth = self.tooth_width.getValue()
width = self.width.getValue()
outer_radius = pitch*teeth / math.pi /2
inner_radius = outer_radius - tooth_depth/2.0 - self.tooth_depth_offset.getValue()
max_stepdown=self.stepDepth.getValue()
tool_radius = self.tool.getValue().diameter.value/2.0
traverse_height=outer_radius+self.traverseHeight.getValue()
angle=360/teeth
tool_radius = self.tool.getValue().diameter.value/2.0
current_depth=outer_radius
x=0
y=0
z=current_depth
a=0
while current_depth>inner_radius:
d=current_depth
current_depth -= max_stepdown
if current_depth<inner_radius:
current_depth = inner_radius
for i in range(0,int(teeth)):
a = i*angle
path.append(GPoint(position=[x, y, traverse_height], rotation = [a,0,0], rapid=True))
z=current_depth
path.append(GPoint(position=([x,y,z])))
x = width
path.append(GPoint(position=([x, y, z])))
x = 0
path.append(GPoint(position=([x, y, z])))
path.append(GPoint(position=[x, y, traverse_height], rapid=True))
self.path.path += path
path=[]
# widening and cutting the flanks of the teeth
widening = tooth_depth/2.0 - tool_radius
widening_angle = widening / inner_radius
flank_angle = angle*self.tooth_flank_factor.getValue()
for i in range(0,int(teeth)):
a = i*angle- flank_angle - widening_angle * 180/PI
x = 0
y = (current_depth+tool_radius) * sin(flank_angle * pi / 180)
path.append(GPoint(position=[x, y, traverse_height], rotation = [a,0,0], rapid=True))
z=cos(flank_angle * pi/180) * current_depth
path.append(GPoint(position=[x,y,z]))
x = width
path.append(GPoint(position=[x, y, z]))
path.append(GPoint(position=[x, y, traverse_height], rotation = [a,0,0], rapid=True))
a = i * angle + flank_angle + widening_angle * 180 / PI
y = -(current_depth + tool_radius) * sin(flank_angle * pi / 180)
path.append(GPoint(position=[x, y, traverse_height], rotation = [a,0,0], rapid=True))
path.append(GPoint(position=[x, y, z], rotation = [a,0,0]))
x = 0
path.append(GPoint(position=[x, y, z]))
path.append(GPoint(position=[x, y, traverse_height], rapid=True))
self.path.path += path
path = []
# chamfering
chamfer_angle = 45
chamfering_depth = self.chamfering_depth.getValue()
for i in range(0,int(teeth)):
a = i*angle- chamfer_angle - widening_angle * 180/PI
x = 0
y = (outer_radius+tool_radius/2-chamfering_depth) * sin(chamfer_angle * pi / 180)
path.append(GPoint(position=[x, y, traverse_height], rotation = [a,0,0], rapid=True))
z=cos(chamfer_angle * pi/180) * (current_depth+tool_radius)
path.append(GPoint(position=[x,y,z]))
x = width
path.append(GPoint(position=[x, y, z]))
path.append(GPoint(position=[x, y, traverse_height], rotation = [a,0,0], rapid=True))
for i in range(0, int(teeth)):
a = i * angle + chamfer_angle + widening_angle * 180 / PI
x = width
y = -(outer_radius+tool_radius/2-chamfering_depth) * sin(chamfer_angle * pi / 180)
path.append(GPoint(position=[x, y, traverse_height], rotation = [a,0,0], rapid=True))
path.append(GPoint(position=[x, y, z], rotation = [a,0,0]))
x = 0
path.append(GPoint(position=[x, y, z]))
path.append(GPoint(position=[x, y, traverse_height], rapid=True))
path.append(GPoint(position=[0, 0, traverse_height], rotation = [0,0,0], rapid=True))
self.path.path += path
path = []
if self.viewUpdater!=None:
self.viewUpdater(self.path)
def calcPath(self):
return self.path
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,316 | codemakeshare/g-mint | refs/heads/master | /geometry.py | import math
from numpy import *
PI=3.1415926
def vec(arr):
return transpose(matrix(arr))
def sgn(x):
if x>0:
return 1
else:
return -1
def norm(u):
tmp=0
for i in range(0, len(u)):
tmp+=u[i]*u[i]
return float(math.sqrt(tmp))
def dist(u, v):
return norm([u[i]-v[i] for i in range(0, len(u))])
def dist2D(u, v):
return norm([u[i]-v[i] for i in range(0, 2)])
def normalize(u):
tmp=0
for i in range(0, len(u)):
tmp+=u[i]**2
length=float(math.sqrt(tmp))
return array(u)/length
def scapro(u, v):
tmp=0
for i in range(0, len(u)):
tmp+=u[i]*v[i]
return tmp
def crossproduct(u,v):
return array([u[1]*v[2] - u[2]*v[1], u[2]*v[0] - u[0]*v[2], u[0]*v[1] - u[1]*v[0]])
def is_num_equal(a, b, tolerance=0.0001):
return abs(a-b)<tolerance
def frange(left, right, step):
return [left+i*step for i in range(0,int((right-left)/step))]
def calc_angle(u, v):
s=scapro(normalize(u), normalize(v))
#print s
return math.acos(0.999999*s)
def full_angle2d(u, v):
nu=0.9999*normalize(u)
nv=0.9999*normalize(v)
alpha= math.atan2(nv[1],nv[0]) - math.atan2(nu[1],nu[0])
while alpha<0: alpha+=2.0*math.pi
while alpha>=2.0*math.pi: alpha-=2.0*math.pi
return alpha
def rotate_z(point, angle):
if angle == 0 :
return point
else:
return array([point[0] * cos(angle) + point[1] * sin(angle), -point[0] * sin(angle) + point[1] * cos(angle), point [2]])
def rotate_y(point, angle):
if angle == 0 :
return point
else:
return array([point[0] * cos(angle) + point[2] * sin(angle), point[1], -point[0] * sin(angle) + point[2] * cos(angle)])
def rotate_x(point, angle):
if angle == 0 :
return point
else:
return array([point[0], point[1] * cos(angle) + point[2] * sin(angle), -point[1] * sin(angle) + point[2] * cos(angle)])
def mid_point(p1, p2):
return [(p1[i]+p2[i])/2.0 for i in range(0, min(len(p1), len(p2)))]
def diff(p1, p2):
return [(p1[i]-p2[i])for i in range(0, min(len(p1), len(p2)))]
def shares_points(vertices1, vertices2):
result=0
for v1 in vertices1:
for v2 in vertices2:
if tuple(v1)==tuple(v2):
result+=1
return result
def pmin(x,y):
return [min(x[i], y[i])for i in range(0,len(x))]
def pmax(x,y):
return [max(x[i], y[i])for i in range(0,len(x))]
# checks if point p is left (or right) of line a to b (2D). returns 1 if left, -1 if right, 0 if colinear
def isLeft(a, b, p) :
return ((b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]));
def SameSide(p1,p2, a,b):
cp1 = crossproduct(b-a, p1-a)
cp2 = crossproduct(b-a, p2-a)
return (scapro(cp1, cp2) >= 0)
def PointInTriangle(p, vertices):
a=vertices[0]
b=vertices[1]
c=vertices[2]
return ((SameSide(p,a, b,c) and SameSide(p,b, a,c)) and SameSide(p,c, a,b))
def getPlaneHeight(location, triangleVertices):
a=triangleVertices[0]
b=triangleVertices[1]
c=triangleVertices[2]
l=location
denom=((b[1] - c[1])*(a[0] - c[0]) + (c[0] - b[0])*(a[1] - c[1]))
#if is_num_equal(denom, 0.0, 0.000001):
if denom==0.0:
return False, [0, 0, 0], False
u = ((b[1] - c[1])*(l[0] - c[0]) + (c[0] - b[0])*(l[1] - c[1])) / denom
v = ((c[1] - a[1])*(l[0] - c[0]) + (a[0] - c[0])*(l[1] - c[1])) / denom
w = 1.0 - u - v;
# Check if point is in triangle
inTriangle=False
onEdge=False
if (u >= 0.0) and (v >= 0.0) and (w >=0.0):
inTriangle=True
onEdge=is_num_equal(abs(u)+abs(v)+abs(w), 0.0, 0.00000001)
projectedPoint=[u*a[0]+v*b[0]+ w*c[0], u*a[1]+v*b[1]+w*c[1], u*a[2]+v*b[2] +w*c[2]]
return inTriangle, projectedPoint, onEdge
def closestPointOnLineSegment2D(a, b, x, y):
ab=[b[0]-a[0], b[1]-a[1], b[2]-a[2]]
pa=[x-a[0], y-a[1]]
if ab[0]==0.0 and ab[1]==0.0:
return [a[0], a[1], max(a[2], b[2])]
t= (ab[0]*pa[0]+ab[1]*pa[1]) / (ab[0]*ab[0]+ab[1]*ab[1])
t=max(0.0, min(1.0, t))
return [a[0]+t*ab[0], a[1]+t*ab[1], a[2]+t*ab[2]]
def closestPointOnLineSegment(a, b, p):
ab=[b[0]-a[0], b[1]-a[1], b[2]-a[2]]
pa=[p[0]-a[0], p[1]-a[1], p[2]-a[2]]
ab_sp=(ab[0]*ab[0]+ab[1]*ab[1]+ab[2]*ab[2])
if ab_sp==0.0:
return a
t= (ab[0]*pa[0]+ab[1]*pa[1]+ab[2]*pa[2]) / ab_sp
t=max(0.0, min(1.0, t))
return [a[0]+t*ab[0], a[1]+t*ab[1], a[2]+t*ab[2]]
def intersectLineSegments2D(A, B, C, D):
E = (B[0] - A[0], B[1] - A[1])
F = (D[0] - C[0], D[1] - C[1])
P = (-E[1], E[0])
det = scapro(F, P)
if det != 0:
h = scapro([A[0] - C[0], A[1] - C[1]], P) / det
if (h>=0) and (h<=1): #line segments intersect
return [C[0]+h*F[0], C[1]+h*F[1]]
else:
return None
else: # lines parallel
return None
def intersectLineOriginCircle2D(a, b, rad):
dx = b[0] -a[0]
dy = b[1] - a[1]
dr = sqrt(dx**2+dy**2)
D = a[0]*b[1] -b[0]*a[1]
det = rad**2 * dr**2 - D**2
if det<0: # no intersection
return []
elif det>=0: #tangent
p1 = [(D*dy + sgn(dy)*dx*sqrt(det)) / dr**2.0, (-D*dx + abs(dy)*sqrt(det))/dr**2.0]
result = [p1]
if det>0: #two points
p2 = [(D*dy - sgn(dy)*dx*sqrt(det)) / dr**2.0, (-D*dx - abs(dy)*sqrt(det))/dr**2.0]
result.append(p2)
return result
def intersectLineCircle2D(a, b, center, rad):
points = intersectLineOriginCircle2D([a[0]-center[0], a[1]-center[1]], [b[0]-center[0], b[1]-center[1]], rad)
result = [[p[0]+center[0], p[1]+center[1]] for p in points]
return result
def findCircleCenter(p1, p2, p3):
center = [0.0, 0.0, 0.0]
if len(p1)>2:
center[2] = p1[2]
ax = (p1[0] + p2[0]) / 2.0
ay = (p1[1] + p2[1]) / 2.0
ux = (p1[1] - p2[1])
uy = (p2[0] - p1[0])
bx = (p2[0] + p3[0]) / 2.0
by = (p2[1] + p3[1]) / 2.0
vx = (p2[1] - p3[1])
vy = (p3[0] - p2[0])
dx = ax - bx
dy = ay - by
vu = vx * uy - vy * ux
if (vu == 0):
return None, 0 # Points are colinear, so no unique solution
g = (dx * uy - dy * ux) / vu
center[0] = bx + g * vx
center[1] = by + g * vy
radius = (dist(p1, center) + dist(p2, center) + dist(p3, center))/3.0
return center, radius
def dropSphereLine(a, b, p, r):
#assume that a=(0,0,0) and transform everything into that frame of reference:
#line vector:
u=(b[0]-a[0])
v=(b[1]-a[1])
w=(b[2]-a[2])
x=(p[0]-a[0])
y=(p[1]-a[1])
#solve for z (positive sqrt is sufficient)
squared=-(u**2+v**2+w**2) * (-r**2 *u**2-r**2 *v**2+u**2 *y**2 - 2 * u *v*x*y+v**2* x**2)
if squared>=0 and (u**2+v**2)!=0.0:
z = (math.sqrt(squared)+u* w *x+v *w *y)/(u**2+v**2)
m=(u*x+v*y+w*z) / (u**2+v**2+w**2)
if (m>=0) and (m<=1):
return True, z+a[2]-r
return False, 0
def dropSpherePoint(v, x, y, radius):
dx=(v[0]-x)
dy=(v[1]-y)
rs=radius*radius
r2ds=dx*dx+dy*dy
if r2ds<=rs:
h=math.sqrt(rs-r2ds)
pp=v[2]+h-radius
return True, pp
else:
return False, 0
def horizontalLineSlice(p1, p2, slice_level, tolerance_offset = 0.0):
p_slice=None
t_slice_level = slice_level+tolerance_offset
if (p1[2]<t_slice_level and p2[2]>=t_slice_level) or (p1[2]>=t_slice_level and p2[2]<t_slice_level):
ratio = (t_slice_level - p1[2]) / (p2[2] - p1[2])
p_slice = (p1[0] + ratio * (p2[0]-p1[0]), p1[1] + ratio * (p2[1]-p1[1]), slice_level)
return p_slice
# computes the total length of a closed polygon
def polygon_closed_length(poly):
length = sum([dist(poly[i].position, poly[i+1].position) for i in range(0, len(poly)-1)])
# add last line segment between start and finish
length+=dist(poly[0].position, poly[-1].position)
return length
def polygon_closed_length2D(poly):
length = sum([dist2D(poly[i].position, poly[i+1].position) for i in range(0, len(poly)-1)])
# add last line segment between start and finish
length+=dist2D(poly[0].position, poly[-1].position)
return length
def polygon_point_at_position(poly, length):
n = len(poly)
running_dist = 0
for i in range(n + 1):
dist_before = running_dist
p1, p2 = poly[(i - 1) % n].position, poly[i % n].position
line_length = dist2D(p1, p2)
running_dist += line_length
if running_dist>length: # crossed the position, so we insert a point on the current line segment
frac = (length - dist_before) / line_length # relative position along current line segment
print("frac", frac, "ll", line_length)
newp = [(1.0 - frac) * (p1[0]) + frac * p2[0],
(1.0 - frac) * (p1[1]) + frac * p2[1],
(1.0 - frac) * (p1[2]) + frac * p2[2]]
return i, newp
return None
# calculate if polygon is clockwise or counterclockwise. Returns area of polygon (positive if clockwise, negative for counterclockwise)
def polygon_chirality(poly):
n = len(poly)
area2=0
p1x,p1y = poly[0][0:2]
for i in range(n+1):
p2x,p2y = poly[i % n][0:2]
area2 += (p2x-p1x)*(p2y+p1y)
p1x,p1y = p2x,p2y
return area2/2.0
def polygon_bounding_box(poly):
separated = list(zip(*poly)) # split into x, y, z components
bb = [[min(separated[0]), min(separated[1]), min(separated[2])], [max(separated[0]), max(separated[1]), max(separated[2])]]
return bb
# determine if a point is inside a given polygon or not
# Polygon is a list of (x,y) pairs.
def point_inside_polygon(x,y,poly):
n = len(poly)
inside =False
p1x,p1y = poly[0][0:2]
for i in range(n+1):
p2x,p2y = poly[i % n][0:2]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xinters = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xinters:
inside = not inside
p1x,p1y = p2x,p2y
if polygon_chirality(poly)<0:
return inside
else:
return not inside
# find the distance to closest point on polygon boundary to a given point (also returns the point and the index just before that point)
def closest_point_on_polygon(p, poly):
n = len(poly)
p=p
p1 = poly[0]
closest_point = p1
closest_distance=dist(p, closest_point)
closest_index= 0
for i in range(0, n+1):
p2= poly[i % n]
new_close_point = closestPointOnLineSegment(p1, p2, p)
if dist(new_close_point, p)<closest_distance:
closest_distance = dist(new_close_point, p)
closest_point = new_close_point
closest_index=i
p1=p2
return closest_distance, closest_point, closest_index
# find the distance to closest point on polygon boundary to a given point (also returns the point and the index just before that point)
def closest_point_on_open_polygon(p, poly):
n = len(poly)
p=p
p1 = poly[0]
closest_point = p1
closest_distance=dist(p, closest_point)
closest_index= 0
for i in range(0, n):
p2= poly[i % n]
new_close_point = closestPointOnLineSegment(p1, p2, p)
if dist(new_close_point, p)<closest_distance:
closest_distance = dist(new_close_point, p)
closest_point = new_close_point
closest_index=i
p1=p2
return closest_distance, closest_point, closest_index
def path_colinear_error(poly): # gives biggest deviation of points between first and last point
n = len(poly)
if len(poly)<3:
return 0 # two or less points are colinear by definition
p1 = poly[0]
p2 = poly[-1]
furthest_index= 0
error = 0.0
for i in range(1, n-1):
p= poly[i]
new_close_point = closestPointOnLineSegment(p1, p2, p)
if dist(new_close_point, p)>error:
error = dist(new_close_point, p)
furthest_index=i
return error, furthest_index
# intersects a line segment with a polygon and returns all points ordered by distance to A
def intersectLinePolygon(a, b, poly) :
n = len(poly)
p1 = poly[0]
points = []
for i in range(1, n+1):
p2= poly[i % n]
px = intersectLineSegments2D(a, b, p1, p2)
if px is not None:
points.append(px)
p1=p2
points.sort(key=lambda x: dist(x, a))
return points
# intersects a line segment with a polygon and returns all points ordered by distance to A
def intersectLinePolygonBracketed(a, b, poly) :
n = len(poly)
p1 = poly[0]
previous = 0
points = []
for i in range(1, n+1):
p2= poly[i % n]
px = intersectLineSegments2D(a, b, p1, p2)
if px is not None:
points.append([px, poly, previous, i])
p1=p2
previous = i
points.sort(key=lambda e: dist(e[0], a))
return points
def polygon_inside(poly1, poly2):
if polygon_chirality(poly1) * polygon_chirality(poly2) <0:
return False
return point_inside_polygon(poly1[0][0], poly1[0][1], poly2)
# determine if polygons are nested
# Polygon is a list of (x,y) pairs.
def polygons_nested(poly1, poly2):
if polygon_chirality(poly1) * polygon_chirality(poly2) < 0:
return False
return point_inside_polygon(poly1[0][0], poly1[0][1], poly2) or point_inside_polygon(poly2[0][0], poly2[0][1], poly1)
class normalset:
def __init__(self):
self.normals=[];
self.avg_normal=[0,0,0]
def calcNormal(self):
self.avg_normal=array([0.0,0.0,0.0], 'float')
c=0
for n in self.normals:
self.avg_normal=self.avg_normal+array(n,'float')
c=c+1
self.avg_normal=[x/float(c) for x in self.avg_normal]
return self.avg_normal
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,317 | codemakeshare/g-mint | refs/heads/master | /tools/tool.py | import math
from guifw.abstractparameters import *
class Tool(ItemWithParameters):
def __init__(self, name=None, diameter=6, shape='slot', viewer=None, **kwargs):
ItemWithParameters.__init__(self, **kwargs)
if name==None:
self.name=TextParameter(parent=self, name="Description", value="%s cutter - %smm"%(shape, diameter))
else:
self.name=TextParameter(parent=self, name="Description", value=name)
self.shape =ChoiceParameter(parent=self, name="Cutter type", choices=['ball', 'slot', 'ball/heightmap', 'slot/heightmap'], value=shape)
self.diameter=NumericalParameter(parent=self, name="diameter (mm)", value=diameter, min=0.0, step=0.01, callback = self.calculateFeedandSpeed)
self.flutes =NumericalParameter(parent=self, name='flutes', value=2, min=1.0, max=20, step=1, callback = self.calculateFeedandSpeed)
self.chipload =NumericalParameter(parent=self, name='chipload (mm/tooth)', value=0.03, min=0.01, max=1, step=0.001, callback = self.calculateFeedandSpeed)
self.engagement = NumericalParameter(parent=self, name='max. engagement/WOC', value=0.5, min=0.1, max=30, step=0.1, callback = self.calculateFeedandSpeed)
self.maxDOC = NumericalParameter(parent=self, name='max. depth of cut (DOC)', value=10.0, min=0.0, max=100, step=0.1, callback = self.calculateFeedandSpeed)
self.surfacespeed=NumericalParameter(parent=self, name='surface speed (m/min)', value=60, min=1, max=600, step=10, callback = self.calculateFeedandSpeed)
self.spindleRPM=NumericalParameter(parent=self, name='spindle speed (RPM)', value=0, min=1, max=100000, step=1, editable=False)
self.feedrate=NumericalParameter(parent=self, name='feedrate(mm/min)', value=0, min=1, max=20000, step=1, editable=False)
self.specificCuttingForce=NumericalParameter(parent=self, name='spec. cutting force (N/mm^2)', value=700.0, min=0.0, max=20000.0, step=100.0, editable=True, callback = self.calculateFeedandSpeed)
self.mrr =NumericalParameter(parent=self, name='MRR (cm^3/min)', value=0.0, min=0, max=20000, step=1, editable=False)
self.cuttingForce =NumericalParameter(parent=self, name='cutting force', value=0, min=0, max=20000, step=1, editable=False)
self.spindleLoad =NumericalParameter(parent=self, name='spindle load (Watt)', value=0, min=0, max=20000, step=1, editable=False)
self.calculateFeedandSpeed(0)
self.parameters=[self.name, self.shape, self.diameter, self.flutes, self.chipload, self.engagement, self.maxDOC, self.surfacespeed, self.spindleRPM, self.feedrate, self.specificCuttingForce, self.mrr, self.cuttingForce, self.spindleLoad]
def calculateFeedandSpeed(self, val):
if self.diameter.getValue()!=0:
self.spindleRPM.updateValue(1000.0*self.surfacespeed.getValue()/(math.pi*self.diameter.getValue()))
radius = self.diameter.getValue()/2.0
#WOC = radius - sin(ea)*radius = radius (1-cos(ea))
# ea = arcsin(1-(WOC/radius))
adjEngagement = min(self.engagement.getValue(), radius)
engagementAngle = math.acos(1.0-(adjEngagement/radius))
#chipThinningFactor = math.pi/engagementAngle/2.0
chipThinningFactor = 1.0/math.sin(engagementAngle)
self.feedrate.updateValue( self.chipload.getValue() * self.flutes.getValue() * self.spindleRPM.getValue()*chipThinningFactor)
self.mrr.updateValue(self.maxDOC.getValue() * self.engagement.getValue() * self.feedrate.getValue()/1000.0)
h=self.chipload.getValue()
K=1.26
b=self.maxDOC.getValue()
mc=0.25
kc = self.specificCuttingForce.getValue()
self.cuttingForce.updateValue(K*b*h**(1.0-mc) *kc)
machineEfficiency = 0.75
self.spindleLoad.updateValue((self.mrr.getValue() * self.specificCuttingForce.getValue())/60.0/machineEfficiency)
def getType(self):
return "mill"
def getDescription(self):
return "%s cutter - %smm"%(self.shape.getValue(), self.diameter.getValue())
def getHeightFunction(self, model):
if self.shape.getValue()=="ball":
return model.get_height_ball_geometric
if self.shape.getValue()=="slot":
return model.get_height_slotdrill_geometric
elif self.shape.getValue()=="ball/heightmap":
return model.get_height_ball_map
elif self.shape.getValue()=="slot/heightmap":
return model.get_height_slotdrill_map
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,318 | codemakeshare/g-mint | refs/heads/master | /grbldialog.py | from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtWidgets import *
import threading
from builtins import bytes
from objectviewer import *
from tools.pathtool import *
import serial
from guifw.gui_elements import *
import os, fnmatch
class SerialPort(object):
'''auto-detected serial port'''
def __init__(self, device, description=None, hwid=None):
self.device = device
self.description = description
self.hwid = hwid
self.port = None
def open(self, device=None):
if device is not None:
self.device = device
try:
self.port = serial.Serial(str(self.device), 115200, timeout=0, dsrdtr=False, rtscts=False, xonxoff=False)
# self.port.setBaudrate(115200)
# self.port.baudrate=115200
except:
print(self.device, "Serial port not found!")
self.port = None
try:
fd = self.port.fileno()
# set_close_on_exec(fd)
except Exception:
fd = None
print("successfully opened", str(self.device))
time.sleep(1.0)
print("serial port ready.", str(self.device))
def close(self):
if self.port is not None:
print("closing open connection")
self.port.close()
self.port = None
def reopen(self, device=None):
self.close()
self.open(device)
def write_raw(self, bmsg):
if self.port is not None:
self.port.write(bmsg)
def write(self, msg):
if self.port is not None:
self.port.write(msg.encode('iso-8859-1'))
def flush(self):
if self.port is not None:
self.port.flush()
def __str__(self):
ret = self.device
if self.description is not None:
ret += " : " + self.description
if self.hwid is not None:
ret += " : " + self.hwid
return ret
def auto_detect_serial_win32(preferred_list=['*']):
'''try to auto-detect serial ports on win32'''
try:
from serial.tools.list_ports_windows import comports
list = sorted(comports())
except:
return []
ret = []
others = []
for port, description, hwid in list:
matches = False
p = SerialPort(port, description=description, hwid=hwid)
for preferred in preferred_list:
if fnmatch.fnmatch(description, preferred) or fnmatch.fnmatch(hwid, preferred):
matches = True
if matches:
ret.append(p)
else:
others.append(p)
if len(ret) > 0:
return ret
# now the rest
ret.extend(others)
return ret
def auto_detect_serial_unix(preferred_list=['*']):
'''try to auto-detect serial ports on unix'''
import glob
# glist = glob.glob('/dev/ttyS*') + glob.glob('/dev/ttyUSB*') + glob.glob('/dev/ttyACM*') + glob.glob('/dev/serial/by-id/*')
glist = glob.glob('/dev/ttyUSB*') + glob.glob('/dev/ttyACM*') + glob.glob('/dev/serial/by-id/*') + glob.glob('/dev/tty.usb*') + glob.glob('/dev/tty.wchusb*')
ret = []
others = []
# try preferred ones first
for d in glist:
matches = False
for preferred in preferred_list:
if fnmatch.fnmatch(d, preferred):
matches = True
if matches:
ret.append(SerialPort(d))
else:
others.append(SerialPort(d))
if len(ret) > 0:
return ret
ret.extend(others)
return ret
def auto_detect_serial(preferred_list=['*']):
'''try to auto-detect serial port'''
# see if
if os.name == 'nt':
return auto_detect_serial_win32(preferred_list=preferred_list)
return auto_detect_serial_unix(preferred_list=preferred_list)
class GrblInterface():
def __init__(self, portname="/dev/ttyUSB0"):
self.read_timer = QtCore.QTimer()
self.read_timer.setInterval(2)
self.read_timer.timeout.connect(self.readSerial)
self.serial = SerialPort("")
self.reopenSerial(portname)
self.receive_buffer = ""
self.pending = False
self.jogging = False
self.update_pending = True
self.feedrate = 1000
self.axes = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] # coordinates in work coordinate space
self.m_axes = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] # coordinates in machine space
self.offsets = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
self.overrides = [100.0, 100.0, 100.0]
self.current_jog_dir=[0.0, 0.0, 0.0]
self.jog_scale = [1000, 1000, 1000]
self.actualFeed = 0.0
self.status = ""
self.status_callback = None
self.last_transmission_timer = 10000
def reopenSerial(self, device=None):
# self.read_timer.stop()
self.read_timer.setInterval(1000)
self.serial.close()
self.serial.open(device)
if self.serial.port is not None:
self.read_timer.setInterval(2)
self.read_timer.start()
else:
print("Serial connection closed.")
def readSerial(self):
if self.serial.port is None:
self.reopenSerial()
self.read_timer.setInterval(1000)
return
try:
self.receive_buffer += self.serial.port.read(200).decode('iso-8859-1')
except serial.SerialException:
self.reopenSerial()
return
lines = self.receive_buffer.split('\n', 1)
while len(lines) > 1:
line = lines[0].strip()
self.receive_buffer = lines[1]
if len(line) > 0:
print("received:", line)
self.parseGRBLStatus(line.strip())
lines = self.receive_buffer.split('\n', 1)
# get more updates if not idle, or for a certain time after the last transmission
# (to capture short movements, to avoid missing the Idle->Jog->Idle transition)
if (self.status != "Idle" or self.last_transmission_timer < 200) and \
((self.last_transmission_timer % 500) == 0 or (
not self.update_pending and (self.last_transmission_timer % 100) == 0)):
self.getUpdate()
self.last_transmission_timer += 1
# check if we stopped jogging and machine is still moving - keep sending stop commands
if not self.jogging and self.status == "Jog" and (self.last_transmission_timer % 20) == 0:
self.stopJog()
def parseGRBLStatus(self, line):
try:
if line == "ok":
self.pending = False
elif len(line) > 5 and line[0:5] == "error":
self.pending = False
print("ERROR:", line)
elif len(line) > 1 and line[0] == '<':
self.update_pending = False
parts = line.split(">")[0].split("|")
self.status = parts[0][1:]
for i in range(1, len(parts)):
part = parts[i]
if part[0:5] == "MPos:":
self.m_axes = [float(c) for c in part[5:].split(",")]
self.axes = [self.m_axes[i]-self.offsets[i] for i in range(0, len(self.m_axes))]
if part[0:5] == "WPos:":
self.axes = [float(c) for c in part[5:].split(",")]
self.m_axes = [self.axes[i]+self.offsets[i] for i in range(0, len(self.axes))]
if part[0:4] == "WCO:":
self.offsets = [float(c) for c in part[4:].split(",")]
if part[0:3] == "Ov:":
self.overrides = [float(c) for c in part[3:].split(",")]
if part[0:3] == "Ov:":
self.overrides = [float(c) for c in part[3:].split(",")]
print("overrides: ", self.overrides)
if part[0:3] == "FS:":
self.actualFeed = [float(c) for c in part[3:].split(",")]
except Exception as e:
print("GRBL parse error:", line, e)
# print self.status, "mpos:", self.axes, "off:", self.offsets
if self.status_callback is not None:
self.status_callback(self)
def sendGCommand(self, gcode):
self.serial.write(gcode)
self.serial.write("\n")
self.serial.flush()
print("sent:", gcode)
self.pending = True
self.last_transmission_timer = 0
def sendFeedHold(self):
self.serial.write("!")
self.serial.flush()
print("feed hold")
def sendResume(self):
self.serial.write("~")
self.serial.flush()
print("resume")
def sendCancel(self):
self.serial.write_raw(b'\x18') # send a Ctrl-X (cancel/abort)
self.serial.flush()
print("cancel")
def startJog(self, command):
gcode = ""
if command == "xm":
self.current_jog_dir[0]=-1 * self.jog_scale[0]
if command == "xp":
self.current_jog_dir[0]=1 * self.jog_scale[0]
if command == "ym":
self.current_jog_dir[1]=-1 * self.jog_scale[1]
if command == "yp":
self.current_jog_dir[1]=1 * self.jog_scale[1]
if command == "zm":
self.current_jog_dir[2]=-1 * self.jog_scale[2]
if command == "zp":
self.current_jog_dir[2]=1 * self.jog_scale[2]
if command == "am":
gcode = "$J=G91A-1000F%i\n?" % (self.feedrate)
if command == "ap":
gcode = "$J=G91A1000F%i\n?" % (self.feedrate)
if command == "bm":
gcode = "$J=G91B-1000F%i\n?" % (self.feedrate)
if command == "bp":
gcode = "$J=G91B1000F%i\n?" % (self.feedrate)
if command == "cm":
gcode = "$J=G91C-1000F%i\n?" % (self.feedrate)
if command == "cp":
gcode = "$J=G91C1000F%i\n?" % (self.feedrate)
gcode = "$J=G91X%i Y%i Z%i F%i\n?" % (self.current_jog_dir[0], self.current_jog_dir[1], self.current_jog_dir[2], self.feedrate)
self.serial.write_raw(b'\x85')
self.serial.flush()
self.serial.write(gcode)
self.sendResume()
self.serial.flush()
self.jogging = True
self.last_transmission_timer = 0
self.pending = True
print("sent:", gcode)
def getUpdate(self):
self.serial.write("?")
self.serial.flush()
self.update_pending = True
# print "request update..."
def stopJog(self, command=""):
print("stop jog")
if command == "xm" or command == "xp":
self.current_jog_dir[0]=0
if command == "ym" or command == "yp":
self.current_jog_dir[1]=0
if command == "zm" or command == "zp":
self.current_jog_dir[2]=0
self.serial.write_raw(b'\x85')
self.serial.flush()
self.pending = False
self.jogging = False
self.last_transmission_timer = 0
#if all(v == 0 for v in self.current_jog_dir):
# self.startJog("")
def setFeedOverride(self, value):
currentValue = self.overrides[0]
# self.port.write(b'\x90') #set to programmed rate
tens = int((value - currentValue) / 10)
ones = int((value - currentValue)) - 10 * tens
print(tens, ones)
while tens > 0:
self.serial.write_raw(b'\x91') # increase by 10%
self.serial.write('\n') # increase by 10%
tens -= 1
while ones > 0:
self.serial.write_raw(b'\x93') # increase by 1%
self.serial.write('\n')
ones -= 1
while tens < 0:
self.serial.write_raw(b'\x92') # decrease by 10%
self.serial.write('\n') # increase by 10%
tens += 1
while ones < 0:
self.serial.write_raw(b'\x94') # decrease by 1%
self.serial.write('\n')
ones += 1
self.serial.write('?')
self.serial.flush()
print("send feed override")
class RTButton(QtWidgets.QPushButton):
def __init__(self, name="", command="", machine_interface=None, size=50):
QtWidgets.QPushButton.__init__(self, name)
self.machine_interface = machine_interface
self.setFixedHeight(size)
self.setFixedWidth(size)
self.setAutoRepeat(True)
self.setAutoRepeatDelay(10)
self.setAutoRepeatInterval(50)
self.clicked.connect(self.handleClicked)
self.released.connect(self.handleClicked)
self._state = 0
self.command = command
self.setContentsMargins(0,0,0,0)
def handleClicked(self):
if self.isDown():
if self._state == 0:
self._state = 1
print('start', self.command)
self.machine_interface.startJog(self.command)
else:
# self.machine_interface.startJog(self.command)
# print self.command
None
elif self._state == 1:
self._state = 0
self.machine_interface.stopJog(self.command)
print('stop')
else:
# self.machine_interface.stopJog()
print('click')
class AxisDisplayWidget(LabeledTextField):
def __init__(self, label="", value=None, height=30):
LabeledTextField.__init__(self, label=label, value=value, formatString="{:4.3f}", editable=True)
self.setFixedWidth(250)
self.setFixedHeight(height)
self.font = QtGui.QFont("Helvetica [Cronyx]", 16);
self.setFont(self.font)
self.label.setFixedHeight(30)
self.text.setFixedHeight(height)
self.zero_button = QtWidgets.QPushButton("0")
self.half_button = QtWidgets.QPushButton("1/2")
self.zero_button.pressed.connect(self.zeroButtonPushed)
self.half_button.pressed.connect(self.halfButtonPushed)
self.zero_button.setFixedWidth(45)
self.zero_button.setFixedHeight(height)
self.half_button.setFixedWidth(45)
self.half_button.setFixedHeight(height)
self.layout.addWidget(self.zero_button)
self.layout.addWidget(self.half_button)
self.layout.setContentsMargins(0,0,0,0)
self.layout.setSpacing(0)
def zeroButtonPushed(self):
self.text.setText("0.0")
self.textEditedHandler()
def halfButtonPushed(self):
current_pos = float(self.text.text())
self.text.setText("%f" % (current_pos / 2.0))
self.textEditedHandler()
class AxesWidget(QtWidgets.QWidget):
def __init__(self, machine_interface=None,
display_axes = ["X", "Y", "Z"],
machine_axes=["X", "Y", "Z", "A", "B", "C"],
displayHeight=40):
QtWidgets.QWidget.__init__(self)
self.statuslayout = QtWidgets.QGridLayout()
self.machine_interface = machine_interface
self.setLayout(self.statuslayout)
self.statuslayout.setSpacing(0)
self.statuslayout.setContentsMargins(0,0,0,0)
self.font = QtGui.QFont("Helvetica [Cronyx]", 16);
self.status = QtWidgets.QLabel("---")
self.status.setFixedWidth(150)
self.status.setFixedHeight(25)
self.status.setFont(self.font)
self.statuslayout.addWidget(self.status, 0, 0)
self.actualFeedDisplay = LabeledTextField(label="Feed", value=0.0, formatString="{:4.1f}", editable=False)
self.actualFeedDisplay.setFixedWidth(200)
self.statuslayout.addWidget(self.actualFeedDisplay, 1, 0)
self.machine_axes = machine_axes
self.axes_names = display_axes
self.number_of_axes = len(self.axes_names)
self.wcs_names = ["G53", "G54", "G55", "G56", "G57", "G58", "G59"]
self.position_fields = [AxisDisplayWidget(label=self.axes_names[i], value=0.0, height = displayHeight) for i in
range(0, self.number_of_axes)]
self.wcs_fields = [
CommandButton(name=self.wcs_names[i], width=30, height=30, callback=self.changeWCS, callback_argument=i) for
i in range(0, len(self.wcs_names))]
self.active_wcs = 1
self.wcs_widget = QtWidgets.QWidget()
wcs_layout = QtWidgets.QHBoxLayout()
wcs_layout.setSpacing(0)
wcs_layout.setContentsMargins(0,0,0,0)
self.wcs_widget.setLayout(wcs_layout)
for i in range(0, len(self.wcs_names)):
wcs_layout.addWidget(self.wcs_fields[i])
for i in range(0, self.number_of_axes):
p = self.position_fields[i]
p.edited_callback = self.axisEdited
p.edited_callback_argument = i
self.statuslayout.addWidget(self.position_fields[i], i + 2, 0)
self.statuslayout.addWidget(self.wcs_widget, self.number_of_axes + 2, 0)
self.statuslayout.addWidget(QtWidgets.QLabel(""), 0, 4)
self.machine_interface.status_callback = self.updateStatus
def changeWCS(self, wcs_index):
self.machine_interface.sendGCommand(self.wcs_names[wcs_index] + "\n")
self.active_wcs = wcs_index
def axisEdited(self, index):
new_text = self.position_fields[index].text.text()
try:
new_pos = float(new_text)
print(self.axes_names[index], new_pos)
self.machine_interface.sendGCommand("G10 P%i L20 %s%f" % (self.active_wcs, self.axes_names[index], new_pos))
time.sleep(0.1)
self.machine_interface.getUpdate()
except:
print("invalid number")
self.updateStatus(self.machine_interface)
def updateStatus(self, machine_interface):
self.status.setText(machine_interface.status)
self.actualFeedDisplay.updateValue(machine_interface.actualFeed)
for i in range(0, self.number_of_axes):
if self.machine_axes[i] in self.axes_names:
di = self.axes_names.index(self.machine_axes[i])
self.position_fields[di].updateValue(machine_interface.axes[i])
class CursorWidget(QtWidgets.QWidget):
def __init__(self,
machine_interface=None,
buttonsize=50,
axes = [["<", "xm", QtCore.Qt.Key_Left, 1, 0],
[">", "xp", QtCore.Qt.Key_Right, 1, 2],
["v", "ym", QtCore.Qt.Key_Down, 1, 1],
["^", "yp", QtCore.Qt.Key_Up, 0, 1],
["z-", "zm", QtCore.Qt.Key_PageDown, 1, 3],
["z+", "zp", QtCore.Qt.Key_PageUp, 0, 3]
]):
QtWidgets.QWidget.__init__(self)
cursorlayout = QtWidgets.QGridLayout()
cursorWidget = QtWidgets.QWidget()
layout = QtWidgets.QVBoxLayout()
layout.setSpacing(0)
layout.setContentsMargins(0,0,0,0)
cursorlayout.setSpacing(0)
cursorlayout.setContentsMargins(0,0,0,0)
cursorWidget.setLayout(cursorlayout)
self.machine_interface = machine_interface
self.axes = axes
self.setLayout(layout)
self.axis_buttons=[]
for a in self.axes:
self.axis_buttons.append(RTButton(a[0], command=a[1], machine_interface=machine_interface, size=buttonsize))
cursorlayout.addWidget(self.axis_buttons[-1], a[3], a[4])
self.rapidbutton = QtWidgets.QPushButton("Rapid")
self.rapidbutton.setFixedHeight(buttonsize)
self.rapidbutton.setFixedWidth(buttonsize)
self.rapidbutton.clicked.connect(self.rapidButtonClicked)
self.rapidbutton.setCheckable(True)
cursorlayout.addWidget(self.rapidbutton, 0, 0)
columns=max([a[4] for a in self.axes])+1
cursorWidget.setFixedWidth(buttonsize*columns +2)
cursorWidget.setFixedHeight(buttonsize*2 +2)
layout.addWidget(cursorWidget)
self.jogfeed = LabeledNumberField(label="Jogspeed", min=0, max=1000, value=400, step=50, slider=True)
self.jogfeed.number.valueChanged.connect(self.rapidButtonClicked)
self.rapidfeed = LabeledNumberField(label="Rapid speed", min=0, max=8000, value=2000, step=50)#, slider=False)
layout.addWidget(self.rapidfeed)
layout.addWidget(self.jogfeed)
#self.setFixedWidth(buttonsize*4 +35)
self.machine_interface.feedrate = self.jogfeed.number.value()
QtWidgets.qApp.installEventFilter(self)
def rapidButtonClicked(self):
if self.rapidbutton.isChecked():
self.machine_interface.feedrate = self.rapidfeed.number.value()
print("rapid on")
else:
self.machine_interface.feedrate = self.jogfeed.number.value()
print("rapid off")
def eventFilter(self, source, event):
key_caught = False
if not self.isVisible(): # ignore events if not visible
return super(CursorWidget, self).eventFilter(source, event)
if event.type() == QtCore.QEvent.KeyPress:
# print('KeyPress: %s [%r]' % (event.key(), source))
key = event.key()
mod = int(event.modifiers())
for a, ab in zip(self.axes, self.axis_buttons):
if key == a[2]:
if not event.isAutoRepeat():
ab.setDown(True)
key_caught=True
if key == QtCore.Qt.Key_Shift:
self.rapidbutton.setChecked(True)
self.rapidButtonClicked()
return True
elif event.type() == QtCore.QEvent.KeyRelease:
# print('KeyRelease: %s [%r]' % (event.key(), source))
key = event.key()
mod = int(event.modifiers())
for a, ab in zip(self.axes, self.axis_buttons):
if key == a[2]:
if not event.isAutoRepeat():
ab.setDown(False)
ab.handleClicked()
key_caught = True
if key == QtCore.Qt.Key_Shift:
self.rapidbutton.setChecked(False)
self.rapidButtonClicked()
return True
# not a filtered key
if not key_caught:
return super(CursorWidget, self).eventFilter(source, event)
else:
return True
class GCodeWidget(QtWidgets.QWidget):
def __init__(self, machine_interface=None, path_dialog=None, editor=None):
QtWidgets.QWidget.__init__(self)
self.path_dialog = path_dialog
self.machine_interface = machine_interface
self.current_gcode = []
self.current_line_number = 0
buttonlayout = QtWidgets.QHBoxLayout()
self.buttonwidget = QtWidgets.QWidget()
self.buttonwidget.setLayout(buttonlayout)
self.layout = QtWidgets.QVBoxLayout()
self.layout.setSpacing(0)
self.editor=editor
self.setLayout(self.layout)
self.startButton = QtWidgets.QPushButton("Start")
self.startButton.setToolTip("F5")
self.startButton.setFixedWidth(60)
self.startButton.setFixedHeight(30)
self.startButton.pressed.connect(self.startPushed)
self.stopButton = QtWidgets.QPushButton("Stop")
self.stopButton.setToolTip("ESC")
self.stopButton.setFixedWidth(60)
self.stopButton.setFixedHeight(30)
self.stopButton.pressed.connect(self.stopPushed)
self.pauseButton = QtWidgets.QPushButton("Hold")
self.pauseButton.setToolTip("H")
self.pauseButton.setFixedWidth(60)
self.pauseButton.setFixedHeight(30)
self.pauseButton.clicked.connect(self.pausePushed)
self.pauseButton.setCheckable(True)
self.stepButton = QtWidgets.QPushButton("Step")
self.stepButton.setFixedWidth(60)
self.stepButton.setFixedHeight(30)
self.stepButton.clicked.connect(self.sendGCode)
buttonlayout.addWidget(self.startButton)
buttonlayout.addWidget(self.stopButton)
buttonlayout.addWidget(self.pauseButton)
buttonlayout.addWidget(self.stepButton)
buttonlayout.addStretch()
buttonlayout.setSpacing(0)
self.layout.setSpacing(0)
self.layout.setContentsMargins(0,0,0,0)
self.layout.addWidget(self.buttonwidget)
self.repeatProgram = LabeledNumberField(label="repeats", value=0, min=0, step=1.0)
self.layout.addWidget(self.repeatProgram)
self.feedrate_override = LabeledNumberField(label="Feedrate override", min=0, max=200, value=100, step=1.0,
slider=True)
self.feedrate_override.number.valueChanged.connect(self.feedrateOverrideHandler)
self.feedrate_override.setFixedWidth(200)
self.layout.addWidget(self.feedrate_override)
self.manual_enter = QtWidgets.QLineEdit(parent=self)
self.manual_enter.returnPressed.connect(self.manualGCodeHandler)
self.layout.addWidget(self.manual_enter)
self.send_timer = QtCore.QTimer()
self.send_timer.setInterval(1)
self.send_timer.timeout.connect(self.sendGCode)
QtWidgets.qApp.installEventFilter(self)
def feedrateOverrideHandler(self):
feedrate_override = self.feedrate_override.number.value()
self.machine_interface.setFeedOverride(feedrate_override)
def manualGCodeHandler(self):
command = str(self.manual_enter.text())
print("sending:", command)
self.machine_interface.sendGCommand(command)
self.manual_enter.clear()
def sendGCode(self):
if self.machine_interface.pending:
#None
return
if self.current_line_number < len(self.current_gcode):
self.machine_interface.sendGCommand(self.current_gcode[self.current_line_number])
if self.editor is not None:
self.editor.highlightLine(self.current_line_number, refresh = True)
self.current_line_number += 1
else:
repeats = self.repeatProgram.number.value()
if repeats>1: # repeat program specified number of times
#decrement counter
self.repeatProgram.updateValue(repeats - 1)
# reset line number to restart program
self.current_line_number = 0
else: # if no repeats, stop program
self.send_timer.stop()
def startPushed(self):
if self.editor is not None:
self.current_gcode = self.editor.getText()
elif self.path_dialog is not None and self.path_dialog.pathtab.selectedTool is not None:
gcode = self.path_dialog.pathtab.selectedTool.getCompletePath()
self.current_gcode = gcode.toText().split("\n")
if len(self.current_gcode)>0:
self.current_line_number = 0
if not self.pauseButton.isChecked():
self.send_timer.start()
def stopPushed(self):
self.machine_interface.sendFeedHold()
time.sleep(0.5)
self.machine_interface.sendCancel()
self.pauseButton.setChecked(False)
self.send_timer.stop()
def pausePushed(self):
if self.pauseButton.isChecked():
self.machine_interface.sendFeedHold()
self.send_timer.stop()
print("pause")
else:
self.machine_interface.sendResume()
self.send_timer.start()
print("unpause")
def eventFilter(self, source, event):
key_caught = False
if not self.isVisible(): # ignore events if not visible
return super(GCodeWidget, self).eventFilter(source, event)
if event.type() == QtCore.QEvent.KeyPress:
key = event.key()
mod = int(event.modifiers())
if not event.isAutoRepeat():
if key == QtCore.Qt.Key_H:
self.pauseButton.setChecked(not self.pauseButton.isChecked())
self.pausePushed()
key_caught=True
if key == QtCore.Qt.Key_Escape:
self.stopPushed()
key_caught=True
if key == QtCore.Qt.Key_F5:
self.startPushed()
key_caught=True
if key == QtCore.Qt.Key_F7:
self.sendGCode()
key_caught=True
if event.type() == QtCore.QEvent.KeyRelease:
key = event.key()
mod = int(event.modifiers())
if not event.isAutoRepeat():
#if key == QtCore.Qt.Key_Space:
#self.pauseButton.setChecked(False)
None
if not key_caught:
return super(GCodeWidget, self).eventFilter(source, event)
else:
return True
class GrblDialog(QtWidgets.QWidget):
def __init__(self, path_dialog=None, editor=None, layout="vertical", machine="mill", device = None):
QtWidgets.QWidget.__init__(self)
self.path_dialog = path_dialog
self.machine_interface = GrblInterface(portname=device)
self.serialPorts = []
self.serialSelect = PlainComboField(parent=self, label='Serial port',
choices=[s.device for s in self.serialPorts],
value=self.machine_interface.serial.device,
onOpenCallback=self.rescanForSerials)
self.rescanForSerials()
self.reopenSerial(0)
self.serialSelect.currentIndexChanged.connect(self.reopenSerial)
self.serialSelect.highlighted.connect(self.rescanForSerials)
self.serialSelect.setFixedWidth(100)
axes = [["<", "xm", QtCore.Qt.Key_Left, 1, 0],
[">", "xp", QtCore.Qt.Key_Right, 1, 2],
["v", "ym", QtCore.Qt.Key_Down, 1, 1],
["^", "yp", QtCore.Qt.Key_Up, 0, 1],
["z-", "zm", QtCore.Qt.Key_PageDown, 1, 3],
["z+", "zp", QtCore.Qt.Key_PageUp, 0, 3]]
display_axes = ["X", "Y", "Z"]
if machine == "mill":
axes = [["<", "xm", QtCore.Qt.Key_Left, 1, 0],
[">", "xp", QtCore.Qt.Key_Right, 1, 2],
["v", "ym", QtCore.Qt.Key_Down, 1, 1],
["^", "yp", QtCore.Qt.Key_Up, 0, 1],
["z-", "zm", QtCore.Qt.Key_PageDown, 1, 3],
["z+", "zp", QtCore.Qt.Key_PageUp, 0, 3]]
if machine == "lathe":
axes = [["<", "zm", QtCore.Qt.Key_Left, 1, 0],
[">", "zp", QtCore.Qt.Key_Right, 1, 2],
["v", "xp", QtCore.Qt.Key_Down, 1, 1],
["^", "xm", QtCore.Qt.Key_Up, 0, 1],]
display_axes = ["X", "Y", "Z"]
self.machine_interface.jog_scale[0] = 2000 # scale X axis twice as big in lathe mode (diameter mode, to get 45 degree movement)
if layout == "vertical":
mlayout = QtWidgets.QVBoxLayout()
self.setLayout(mlayout)
mlayout.setSpacing(0)
mlayout.setContentsMargins(0, 0, 0, 0)
mlayout.setSpacing(0)
self.status = AxesWidget(machine_interface=self.machine_interface, display_axes=display_axes,
displayHeight=45)
self.cursors = CursorWidget(machine_interface=self.machine_interface, buttonsize=50, axes=axes)
self.gcode = GCodeWidget(machine_interface=self.machine_interface, path_dialog=self.path_dialog,
editor=editor)
mlayout.addWidget(self.status)
mlayout.addWidget(self.cursors)
mlayout.addWidget(self.gcode)
mlayout.addStretch(0)
mlayout.addWidget(self.serialSelect)
# mlayout.addWidget(self.connectButton)
if layout == "horizontal":
mlayout = QtWidgets.QHBoxLayout()
mlayout.setSpacing(0)
mlayout.setContentsMargins(0, 0, 0, 0)
self.setLayout(mlayout)
self.cursors = CursorWidget(machine_interface=self.machine_interface)
self.status = AxesWidget(machine_interface=self.machine_interface)
self.gcode = GCodeWidget(machine_interface=self.machine_interface, path_dialog=self.path_dialog)
mlayout.addWidget(self.cursors)
mlayout.addWidget(self.gcode)
mlayout.addWidget(self.status)
#mlayout.addStretch(0)
def rescanForSerials(self):
self.serialPorts = auto_detect_serial()
print("found serial ports: ", [s.device for s in self.serialPorts])
self.serialSelect.updateChoices([s.device for s in self.serialPorts])
def reopenSerial(self, index):
if index>=0 and index<len(self.serialPorts):
device=self.serialPorts[index]
print (device)
self.machine_interface.reopenSerial(device)
else:
print("No valid serial port found. ", self.serialPorts, index)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication([])
device = "/dev/ttyUSB0"
if len(sys.argv)>1:
device = sys.argv[1]
grbldialog = GrblDialog(layout="horizontal", device = device)
grbldialog.show()
## Start the Qt event loop
app.exec_()
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,319 | codemakeshare/g-mint | refs/heads/master | /cameraviewer.py | from OrthoGLViewWidget import *
from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import numpy as np
import cv2
class CameraViewer(QtGui.QWidget):
changePixmap = pyqtSignal(QImage)
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent=parent)
self.cap=None
self.image_label = QLabel("waiting for video...")
self.image_label.move(0, 0)
self.image_label.resize(1280, 720)
self.main_layout = QVBoxLayout()
self.main_layout.addWidget(self.image_label)
self.setLayout(self.main_layout)
self.zoomSlider = QSlider(orientation=QtCore.Qt.Horizontal)
self.zoomSlider.setMinimum(100)
self.zoomSlider.setMaximum(300)
self.main_layout.addWidget(self.zoomSlider)
self.read_timer = QtCore.QTimer()
self.read_timer.setInterval(40)
self.read_timer.timeout.connect(self.updateCamera)
self.read_timer.start()
@pyqtSlot(QImage)
def setImage(self, image):
self.image_label.setPixmap(QPixmap.fromImage(image))
def Zoom(self, cv2Object, zoomSize):
old_size = (cv2Object.shape[0], cv2Object.shape[1])
new_size = (int(zoomSize * cv2Object.shape[1]), int(zoomSize * cv2Object.shape[0]))
cv2Object = cv2.resize(cv2Object, new_size)
center = (cv2Object.shape[0] / 2, cv2Object.shape[1] / 2)
cv2Object = cv2Object[int(center[0]-(old_size[0]/2)):int((center[0] +(old_size[0]/2))), int(center[1]-(old_size[1]/2)):int(center[1] + (old_size[0]/2))]
return cv2Object
def updateCamera(self):
if self.isVisible():
if self.cap is not None and self.cap.isOpened():
ret, frame = self.cap.read()
frame = self.Zoom(frame, self.zoomSlider.value()/100.0)
if ret == True:
rgbImage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
h, w, ch = rgbImage.shape
bytesPerLine = ch * w
convertToQtFormat = QtGui.QImage(rgbImage.data, w, h, bytesPerLine, QtGui.QImage.Format_RGB888)
p = convertToQtFormat.scaled(640, 480, Qt.KeepAspectRatio)
#self.changePixmap.emit(p)
self.image_label.setPixmap(QPixmap.fromImage(p))
else:
self.cap = cv2.VideoCapture(0)
self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280);
self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720);
else:
if self.cap is not None:
self.cap.release()
self.cap = None | {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,320 | codemakeshare/g-mint | refs/heads/master | /tools/lathethreadingtool.py | from guifw.abstractparameters import *
from geometry import *
from solids import *
import multiprocessing as mp
import time
import pyclipper
from polygons import *
from gcode import *
from collections import OrderedDict
class LatheThreadingTool(ItemWithParameters):
def __init__(self, model=None, tools=[], viewUpdater=None, **kwargs):
ItemWithParameters.__init__(self, **kwargs)
self.model=None
self.patterns=[]
self.path=None
# remap lathe axis for output. For Visualisation, we use x as long axis and y as cross axis. Output uses Z as long axis, x as cross.
self.axis_mapping=["Z", "X", "Y"]
# scaling factors for output. We use factor -2.0 for x (diameter instead of radius), inverted from negative Y coordinate in viz
self.axis_scaling = [1.0, -2.0, 0.0]
self.presets = OrderedDict([("M4 x 0.7", [ 4, 3.3 , 0.7, 0]),
("M5 x 0.8", [ 5, 4.2 , 0.8, 0]),
("M6 x 1", [ 6, 5.0 , 1.0 , 0]),
("M8 x 1.25", [ 8, 6.75, 1.25, 0]),
("M10 x 1.5",[10, 8.5 , 1.5 , 0]),
("M12 x 1.5",[12, 10.5, 1.5, 0]),
("M12 x 1.75",[12, 10.25, 1.75, 0]),
("M14 x 2", [14, 11.8, 2.0 , 0]),
("M16 x 2", [16, 14 , 2.0 , 0]),
("M20 x 2.5", [20, 17.5, 2.5, 0]),
("NPT 1/8",[0.38*25.4, 0.339*25.4, 1.0/27.0*25.4, 1.7899]),
("NPT 1/4", [13.6, 11.113, 1.0 / 18.0 * 25.4, 1.7899])])
self.output_format = {
"lathe (ZX)": {"mapping": ["Z", "X", "Y"], "scaling": [1.0, -2.0, 0.0]},
"mill (XZ)": {"mapping": ["X", "Z", "Y"], "scaling": [1.0, -1.0, 0.0]}
}
self.outputFormatChoice = ChoiceParameter(parent=self, name="Output format",
choices=list(self.output_format.keys()),
value=list(self.output_format.keys())[0])
self.presetParameter = ChoiceParameter(parent=self, name="Presets", choices=self.presets.keys(), value = "M10 x 1.5", callback = self.loadPreset)
self.tool = ChoiceParameter(parent=self, name="Tool", choices=tools, value=tools[0])
self.viewUpdater=viewUpdater
self.leftBound=NumericalParameter(parent=self, name="left boundary", value=-10, step=0.1, callback = self.generatePath)
self.rightBound=NumericalParameter(parent=self, name="right boundary", value=0, step=0.1, callback = self.generatePath)
self.toolSide=ChoiceParameter(parent=self, name="Tool side", choices=["external", "internal"], value = "external", callback = self.generatePath)
self.direction=ChoiceParameter(parent=self, name="Direction", choices=["right to left", "left to right"], value="right to left", callback = self.generatePath)
self.model=model.object
self.pitch=NumericalParameter(parent=self, name="pitch", value=1.0, min=0.0001, step=0.01, callback = self.generatePath)
self.start_diameter=NumericalParameter(parent=self, name="start diameter", value=10.0, min=0.1, step=0.1, callback = self.generatePath)
self.end_diameter=NumericalParameter(parent=self, name="end diameter", value=10.0, min=0.1, step=0.1, callback = self.generatePath)
self.coneAngle=NumericalParameter(parent=self, name='cone angle', value=0.0, min=-89.9, max=89.9, step=0.01, callback = self.generatePath)
self.stepover=NumericalParameter(parent=self, name="stepover", value=0.2, min=0.0001, step=0.01, callback = self.generatePath)
self.retract = NumericalParameter(parent=self, name="retract", value=1.0, min=0.0001, step=0.1, callback = self.generatePath)
#self.diameter=NumericalParameter(parent=self, name="tool diameter", value=6.0, min=0.0, max=1000.0, step=0.1)
self.parameters=[self.outputFormatChoice, self.presetParameter, [self.leftBound, self.rightBound], self.toolSide, self.direction, self.retract,
self.pitch, self.start_diameter, self.end_diameter, self.coneAngle, self.stepover]
self.patterns=None
self.loadPreset(self.presetParameter)
def setThread(self, outer_diameter, inner_diameter, pitch, angle):
if self.toolSide.getValue()=="external":
self.start_diameter.updateValue(outer_diameter)
self.end_diameter.updateValue(inner_diameter)
else:
self.start_diameter.updateValue(inner_diameter)
self.end_diameter.updateValue(outer_diameter)
# self.diameter.viewRefresh()
self.pitch.updateValue(pitch)
# self.pitch.viewRefresh()
self.coneAngle.updateValue(angle)
self.generatePath(None)
def loadPreset(self, parameter):
params = self.presets[parameter.value]
self.setThread(*params)
def external_thread(self):
offset_path = []
y = -self.start_diameter.getValue()/2.0
retract_y = y-self.retract.getValue()
stepover = self.stepover.getValue()
start_x = self.rightBound.getValue()
end_x = self.leftBound.getValue()
pitch = self.pitch.getValue()
if self.direction.getValue() == "left to right":
start_x = self.leftBound.getValue()
end_x = self.rightBound.getValue()
x=start_x
cone_angle = self.coneAngle.getValue() / 180.0 * PI
cone_offset = abs(start_x-end_x)*sin(cone_angle)
finish_passes=2
# switch to feed per rev mode
#offset_path.append(GCommand("G95"))
total_rotation = -(end_x-start_x) / pitch * 360
while finish_passes>0:
y+=stepover
if (y > -self.end_diameter.getValue()/2.0):
y=-self.end_diameter.getValue()/2.0
finish_passes -= 1 # count down finish passes
offset_path.append(GPoint(position=[start_x, retract_y, 0], rotation=[0,0,0], rapid = True))
offset_path.append(GPoint(position=[start_x, y+cone_offset, 0], rotation=[0,0,0], rapid = True))
#offset_path.append(GCommand("G4 P1"))
offset_path.append(GPoint(position=[end_x, y, 0], rotation=[total_rotation,0,0], rapid = False, feedrate=self.pitch.getValue()))
offset_path.append(GPoint(position=[end_x, retract_y, 0], rotation=[total_rotation,0,0], rapid = True))
offset_path.append(GPoint(position=[start_x, retract_y, 0], rotation = [0,0,0], rapid = True))
# switch back to normal feedrate mode
#offset_path.append(GCommand("G94"))
return offset_path
def internal_thread(self):
offset_path = []
y = -self.start_diameter.getValue()/2.0
retract_y = y+self.retract.getValue()
stepover = self.stepover.getValue()
start_x = self.rightBound.getValue()
end_x = self.leftBound.getValue()
if self.direction.getValue() == "left to right":
start_x = self.leftBound.getValue()
end_x = self.rightBound.getValue()
x=start_x
cone_angle = self.coneAngle.getValue() / 180.0 * PI
cone_offset = abs(start_x-end_x)*sin(cone_angle)
finish_passes=2
offset_path.append(GCommand("G95"))
while finish_passes>0:
y-=stepover
if (y < -self.end_diameter.getValue()/2.0):
y=-self.end_diameter.getValue()/2.0
finish_passes -= 1 # count down finish passes
offset_path.append(GPoint(position=(start_x, retract_y, 0), rapid = True))
offset_path.append(GPoint(position=(start_x, y-cone_offset, 0), rapid = True))
offset_path.append(GCommand("G4 P1"))
offset_path.append(GPoint(position=(end_x, y, 0), rapid = False, feedrate=self.pitch.getValue()))
offset_path.append(GPoint(position=(end_x, retract_y, 0), rapid = True))
offset_path.append(GPoint(position=(start_x, retract_y, 0), rapid = True))
return offset_path
def generatePath(self, parameter=None):
if self.toolSide.getValue()=="external":
offset_path = self.external_thread()
else:
offset_path = self.internal_thread()
#self.path = GCode([p for segment in offset_path for p in segment])
self.path = GCode(offset_path)
self.path.default_feedrate = 50
format = self.outputFormatChoice.getValue()
# remap lathe axis for output. For Visualisation, we use x as long axis and y as cross axis. Output uses Z as long axis, x as cross.
self.axis_mapping = self.output_format[format]["mapping"]
# scaling factors for output. We use factor -2.0 for x (diameter instead of radius), inverted from negative Y coordinate in viz
self.axis_scaling = self.output_format[format]["scaling"]
self.path.applyAxisMapping(self.axis_mapping)
self.path.applyAxisScaling(self.axis_scaling)
self.path.steppingAxis = 1
self.path.applyAxisMapping(self.axis_mapping)
self.path.applyAxisScaling(self.axis_scaling)
if self.viewUpdater!=None:
self.viewUpdater(self.path)
return self.path
def calcPath(self):
self.generatePath()
return self.path
def getCompletePath(self):
return self.calcPath()
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,321 | codemakeshare/g-mint | refs/heads/master | /modeldialog.py | from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtWidgets import *
from tools.modeltool import *
from tools.tool import *
from tools.modeltool import *
from tools.tool import *
from tools.pathtool import *
from tools.milltask import *
from guifw.gui_elements import *
import sys, os, os.path
from solids import *
from objectviewer import *
class ModelDialog(QtWidgets.QWidget):
def __init__(self, viewer):
QtWidgets.QWidget.__init__(self)
mlayout = QtWidgets.QGridLayout()
self.setLayout(mlayout)
loadbutton = QtWidgets.QPushButton("Load")
loadbutton.clicked.connect(self.showDialog)
mlayout.addWidget(loadbutton, 0, 0)
self.modelTool = ModelTool(name="Model", object=None, viewUpdater=self.updateView)
self.toolWidget = ToolPropertyWidget(parent=self, tool=self.modelTool)
mlayout.addWidget(self.toolWidget, 1, 0)
self.viewer = viewer
self.object = Solid()
if len(sys.argv) > 1:
self.loadObject(sys.argv[1])
def updateView(self, mode='mesh'):
if mode == 'mesh':
self.viewer.showFacets(self.modelTool.object)
if mode == 'heightmap':
self.viewer.showHeightMap(self.modelTool.object)
if mode == 'slice':
self.viewer.showFacets(self.modelTool.object)
def showDialog(self):
filename = QtWidgets.QFileDialog.getOpenFileName(self, 'Open file', '', "STL files (*.stl)")[0]
self.loadObject(filename)
def loadObject(self, filename):
if not os.path.isfile(filename):
return
self.object = Solid()
self.object.load(filename)
self.object.__class__ = CAM_Solid
self.modelTool.object = self.object
self.updateView()
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,322 | codemakeshare/g-mint | refs/heads/master | /pathdialog.py | from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtWidgets import *
from collections import OrderedDict
import threading_tool
from tools.pathtool import *
from guifw.gui_elements import *
from objectviewer import *
class PathDialog(QtWidgets.QWidget):
def __init__(self, viewer, tools, availablePathTools = None, editor=None):
QtWidgets.QWidget.__init__(self)
self.viewer = viewer
self.editor = editor
self.layout = QtWidgets.QGridLayout()
self.setLayout(self.layout)
self.availablePathTools = availablePathTools
# itemlist=[threading_tool.ThreadingTool(viewUpdater=self.modeltab.viewer.showPath)]
self.view_updater=None
if self.viewer is not None:
self.view_updater = self.update_view
tool=None
if tools is not None:
tool = tools[0]
self.pathtab = ListWidget(itemlist=[], title="Paths", itemclass=self.availablePathTools,
on_select_cb=self.display_path, viewUpdater=self.view_updater, tool=tool, name="-")
self.layout.addWidget(self.pathtab, 0, 0, 1, 2)
combine_paths_btn = QtWidgets.QPushButton("combine paths")
self.layout.addWidget(combine_paths_btn, 1, 1)
combine_paths_btn.clicked.connect(self.combinePaths)
def combinePaths(self):
checkedItems = self.pathtab.getCheckedItems()
newPath = GCode()
for p in checkedItems:
newPath.appendPath(p.getCompletePath())
if len(checkedItems) > 0:
default_tool = checkedItems[0].tool
self.pathtab.listmodel.addItem(
PathTool(name="combined", path=newPath, viewUpdater=checkedItems[0].viewUpdater, tool=default_tool))
def update_view(self, path, tool):
print('pathdialog update view')
if self.viewer is not None:
print("update path")
self.viewer.showPath(path, tool)
if self.editor is not None:
print("update editor")
self.editor.updateText(path.toText(pure=True))
def display_path(self, pathtool):
global camgui
checkedPaths = self.pathtab.getCheckedItems()
if len(checkedPaths) == 0: # if no paths checked, display the selected path
if self.viewer is not None:
print("pd:", pathtool.tool)
self.viewer.showPath(pathtool.getCompletePath(), tool=pathtool.tool)
if self.editor is not None:
self.editor.updateText(pathtool.getCompletePath().toText(pure=True))
self.editor.setPathTool(pathtool)
else: # otherwise display all checked paths
path = GCode()
for cp in checkedPaths:
path.appendPath(cp.getCompletePath())
if self.viewer is not None:
self.viewer.showPath(path)
if self.editor is not None:
self.editor.updateText(path.toText())
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,323 | codemakeshare/g-mint | refs/heads/master | /objectviewer.py | from OrthoGLViewWidget import *
from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtWidgets import *
import pyqtgraph.opengl as gl
import pyqtgraph as pg
from tools import *
from solids import *
class ObjectViewer(QtWidgets.QWidget):
def __init__(self, parent=None, editor=None):
QtWidgets.QWidget.__init__(self, parent=parent)
self.busy = False
## Create a GL View widget to display data
self.visual_divider = 1
self.pathPlot = None
self.stats = None
self.editor=editor
self.gm = None
self.layout = QtWidgets.QVBoxLayout()
self.setLayout(self.layout)
self.w = OrthoGLViewWidget()
axes = gl.GLAxisItem()
axes.setSize(x=200, y=100, z=100)
self.w.addItem(axes)
# self.w.show()
self.layout.addWidget(self.w)
self.setWindowTitle('CAM preview')
self.w.setCameraPosition(distance=200)
self.stats = QtWidgets.QLabel(parent=self)
self.stats.setMaximumHeight(20)
self.layout.addWidget(self.stats)
self.path_slider = QtWidgets.QSlider(parent=self)
self.path_slider.setOrientation(QtCore.Qt.Horizontal)
self.layout.addWidget(self.path_slider)
self.path_slider.valueChanged.connect(self.updatePathPlot)
# self.show()
self.layout.setSpacing(0)
#self.layout.setMargin(0)
self.resize(800, 600)
# g = gl.GLGridItem()
# g.scale(2,2,1)
# g.setDepthValue(10) # draw grid after surfaces since they may be translucent
# self.w.addItem(g)
self.rawpath = []
self.linecolors = []
self.pointcolors = []
self.gl_cutting_tool = None
def showFacets(self, object):
self.object = object
vertices = array([[v for v in f.vertices] for f in object.facets])
self.mesh = gl.MeshData(vertexes=vertices)
if self.gm != None:
self.w.removeItem(self.gm)
self.gm = gl.GLMeshItem(meshdata=self.mesh, color=(0.0, 0.0, 1.0, 0.5), smooth=False, computeNormals=True,
shader='edgeHilight', glOptions='translucent')
self.w.addItem(self.gm)
def showHeightMap(self, object, visual_divider=4):
if self.gm != None:
self.w.removeItem(self.gm)
self.visual_divider = visual_divider
self.object = object
x_display_size = len(object.xrange) / self.visual_divider
y_display_size = len(object.yrange) / self.visual_divider
xdata = array([object.xrange[x * len(object.xrange) / x_display_size] for x in range(0, x_display_size)])
ydata = array([object.yrange[y * len(object.yrange) / y_display_size] for y in range(0, y_display_size)])
zdata = array([[object.map[x * len(object.xrange) / len(xdata)][y * len(object.yrange) / len(ydata)] for y in
range(0, y_display_size)] for x in range(0, x_display_size)])
self.gm = gl.GLSurfacePlotItem(x=xdata, y=ydata, z=zdata, color=(0.2, 0.0, 0.0, 0.5), shader='edgeHilight',
smooth=False, computeNormals=True)
self.w.addItem(self.gm)
def showHeightMap2(self, object):
self.object = object
vertices = []
m = object.map
xv = object.xrange
yv = object.yrange
for x in range(0, len(object.map) - 1):
for y in range(0, len(object.map[0]) - 1):
vertices.append(
[[xv[x], yv[y], m[x + 1][y]], [xv[x + 1], yv[y], m[x + 1][y]], [xv[x], yv[y + 1], m[x][y + 1]]])
mesh = gl.MeshData(vertexes=array(vertices));
self.p1 = gl.GLMeshItem(meshdata=mesh, color=(0.0, 0.0, 1.0, 0.5), smooth=False, computeNormals=True,
shader='edgeHilight')
self.w.addItem(self.p1)
def showPath(self, path, color=(1.0, 0.0, 0.0, 1.0), width=1, tool = None):
print("showPath", tool)
if tool is not None:
self.showTool(tool)
else:
if self.gl_cutting_tool is not None:
self.w.removeItem(self.gl_cutting_tool)
self.gl_cutting_tool = None
rawpath = path
self.gpoints = None
if path.__class__.__name__ == "GCode":
self.rawpath = []
self.linecolors = []
self.pointcolors = []
self.gpoints = path
self.interpolated = path.get_draw_path(interpolate_arcs=True)
colorcycle = 0.0
# if path.outpaths!=None and len(path.outpaths)>0:
# point_count = sum([len(subpath) for subpath in path.outpaths ])
# for subpath in path.outpaths:
# for p in subpath:
# if p.position is not None:
# self.rawpath.append(p.position)
# point_color=(1.0-(colorcycle/point_count), (colorcycle/point_count), 0.0, 1.0)
# if p.rapid:
# point_color=(1.0, 1.0, 1.0, 1.0)
# if not p.inside_model:
# point_color=(0.0, 0.0, 1.0, 1.0)
# if not p.in_contact:
# point_color=(0.3, 0.3, 0.7, 0.5)
# self.colors.append(point_color)
# colorcycle+=1
# else:
point_count = len(path.path)
for p in path.get_draw_path():
if p.position is not None:
self.rawpath.append(p.position)
point_color = (1.0 - (colorcycle / point_count), (colorcycle / point_count), 0.0, 1.0)
if p.rapid:
point_color = (1.0, 1.0, 1.0, 1.0)
if not p.inside_model:
point_color = (0.0, 0.0, 1.0, 1.0)
if not p.in_contact:
point_color = (0.3, 0.3, 0.7, 0.5)
self.linecolors.append(point_color)
if not p.interpolated:
self.pointcolors.append(point_color)
else:
self.pointcolors.append((0.0,0.0,0.0,0.0))
colorcycle += 1
else:
self.rawpath = []
self.colors = []
for p in path:
# rawpath.append(p[0])
# colors.append((0.5, 0.5, 0.5, 0.5))
self.rawpath += p
self.linecolors += [(float(i) / len(p), float(i) / len(p), float(i) / len(p), 1.0) for i in
range(0, len(p))]
self.rawpath.append(p[-1])
self.pointcolors.append((0.1, 0.1, 0.1, 0.2))
# colors=[color for p in rawpath]
if len(self.rawpath) == 0: return
self.path_slider.setMaximum(len(self.rawpath))
self.path_slider.setValue(len(self.rawpath))
self.updatePathPlot(width)
drawpath = self.rawpath
if self.pathPlot == None:
self.pathPlot = gl.GLLinePlotItem(pos=array(drawpath), color=array(self.linecolors), width=width)
self.pathPlotHighlight = gl.GLScatterPlotItem(pos=array(drawpath), color=array(self.pointcolors), size=3.0)
self.w.addItem(self.pathPlot)
self.w.addItem(self.pathPlotHighlight)
else:
self.pathPlot.setData(pos=array(drawpath), color=array(self.linecolors))
self.pathPlotHighlight.setData(pos=array(drawpath), color=array(self.pointcolors))
def setSelection(self, start_index, end_index):
self.path_slider.blockSignals(True)
self.path_slider.setValue(end_index)
self.path_slider.blockSignals(False)
end_index = self.path_slider.value()
if end_index == 0:
return
if start_index>=end_index:
return
drawpath = self.rawpath[start_index:end_index]
if self.pathPlot is not None:
self.pathPlot.setData(pos=array(drawpath), color=array(self.linecolors[start_index:end_index]))
self.pathPlotHighlight.setData(pos=array(drawpath), color=array(self.pointcolors[start_index:end_index]))
if self.gpoints is not None and len(self.gpoints.path)>end_index-1:
lp = self.gpoints.path[end_index - 1]
feed = self.gpoints.default_feedrate
if lp.feedrate is not None:
feed = lp.feedrate
if lp.feedrate is not None and lp.position is not None:
self.stats.setText("x=% 4.2f y=% 4.2f z=% 4.2f f=%i, line=%i" % (lp.position[0], lp.position[1], lp.position[2], int(feed), lp.line_number))
@staticmethod
def rounded_cylinder(rows, cols, radius=[1.0, 1.0, 0.0], length=1.0, offset=False):
"""
Return a MeshData instance with vertexes and faces computed
for a cylindrical surface.
The cylinder may be tapered with different radii at each end (truncated cone)
"""
verts = np.empty((rows + 1, cols, 3), dtype=float)
if isinstance(radius, int):
radius = [radius, radius, 0.0] # convert to list
## compute vertexes
th = np.linspace(2 * np.pi, 0, cols).reshape(1, cols)
r = np.linspace(radius[0], radius[1], num=rows + 1, endpoint=True).reshape(rows + 1, 1) # radius as a function of z
verts[..., 2] = np.linspace(0, length, num=rows + 1, endpoint=True).reshape(rows + 1, 1) # z
for row in range(rows+1):
if row<rows/3:
ball_section_pos = float(row)/(rows/3.0)
new_z = radius[0]-cos(ball_section_pos*math.pi/2.0) * radius[0]
verts[row,:,2] = new_z
r[row,0] = radius[0] * sin(ball_section_pos*math.pi/2.0)
#print(new_z, radius[0] * sin(ball_section_pos*math.pi/2.0))
else:
verts[row, 2] = float(row-rows/3) / (2*rows / 3.0) * length + radius[2]
#r[row, 0] = 1
if offset:
th = th + ((np.pi / cols) * np.arange(rows + 1).reshape(rows + 1, 1)) ## rotate each row by 1/2 column
verts[..., 0] = r * np.cos(th) # x = r cos(th)
verts[..., 1] = r * np.sin(th) # y = r sin(th)
verts = verts.reshape((rows + 1) * cols, 3) # just reshape: no redundant vertices...
## compute faces
faces = np.empty((rows * cols * 2, 3), dtype=np.uint)
rowtemplate1 = ((np.arange(cols).reshape(cols, 1) + np.array([[0, 1, 0]])) % cols) + np.array([[0, 0, cols]])
rowtemplate2 = ((np.arange(cols).reshape(cols, 1) + np.array([[0, 1, 1]])) % cols) + np.array([[cols, 0, cols]])
for row in range(rows):
start = row * cols * 2
faces[start:start + cols] = rowtemplate1 + row * cols
faces[start + cols:start + (cols * 2)] = rowtemplate2 + row * cols
return gl.MeshData(vertexes=verts, faces=faces)
@staticmethod
def flat_cylinder(rows, cols, radius=[1.0, 1.0, 0.0], length=1.0, offset=False):
"""
Return a MeshData instance with vertexes and faces computed
for a cylindrical surface.
The cylinder may be tapered with different radii at each end (truncated cone)
"""
verts = np.empty((rows + 1, cols, 3), dtype=float)
if isinstance(radius, int):
radius = [radius, radius, 0.0] # convert to list
## compute vertexes
th = np.linspace(2 * np.pi, 0, cols).reshape(1, cols)
r = np.linspace(radius[0], radius[1], num=rows + 1, endpoint=True).reshape(rows + 1, 1) # radius as a function of z
verts[..., 2] = np.linspace(0, length, num=rows + 1, endpoint=True).reshape(rows + 1, 1) # z
r[0,0] = 0
verts[1, :, 2] = 0
if offset:
th = th + ((np.pi / cols) * np.arange(rows + 1).reshape(rows + 1, 1)) ## rotate each row by 1/2 column
verts[..., 0] = r * np.cos(th) # x = r cos(th)
verts[..., 1] = r * np.sin(th) # y = r sin(th)
verts = verts.reshape((rows + 1) * cols, 3) # just reshape: no redundant vertices...
## compute faces
faces = np.empty((rows * cols * 2, 3), dtype=np.uint)
rowtemplate1 = ((np.arange(cols).reshape(cols, 1) + np.array([[0, 1, 0]])) % cols) + np.array([[0, 0, cols]])
rowtemplate2 = ((np.arange(cols).reshape(cols, 1) + np.array([[0, 1, 1]])) % cols) + np.array([[cols, 0, cols]])
for row in range(rows):
start = row * cols * 2
faces[start:start + cols] = rowtemplate1 + row * cols
faces[start + cols:start + (cols * 2)] = rowtemplate2 + row * cols
return gl.MeshData(vertexes=verts, faces=faces)
def showTool(self, tool):
print("showing tool")
if self.gl_cutting_tool is not None:
self.w.removeItem(self.gl_cutting_tool)
self.gl_cutting_tool = None
self.cutting_tool = None
if tool.shape.getValue().startswith("ball"):
self.cutting_tool = ObjectViewer.rounded_cylinder(30, 30, radius=[tool.diameter.getValue()/2.0, tool.diameter.getValue()/2.0, 0], length=30.0)
if tool.shape.getValue().startswith("slot"):
self.cutting_tool = ObjectViewer.flat_cylinder(3, 30, radius=[tool.diameter.getValue() / 2.0, tool.diameter.getValue() / 2.0, 0], length=30.0)
if self.cutting_tool is not None:
self.gl_cutting_tool = gl.GLMeshItem(meshdata=self.cutting_tool, color=(0.8, 0.8, 0.8, 1.0), smooth=True, computeNormals=True, drawEdges=False, shader='shaded', glOptions='translucent')
self.w.addItem(self.gl_cutting_tool)
else:
if self.gl_cutting_tool is not None:
self.w.removeItem(self.gl_cutting_tool)
self.gl_cutting_tool = None
def updatePathPlot(self, width=0.1, updateEditor=True):
end_index = self.path_slider.value()
if updateEditor and self.editor is not None:
self.editor.highlightLine(end_index)
if end_index == 0:
return
drawpath = self.rawpath[0:end_index]
if self.pathPlot is not None:
self.pathPlot.setData(pos=array(drawpath), color=array(self.linecolors[0:end_index]))
self.pathPlotHighlight.setData(pos=array(drawpath), color=array(self.pointcolors[0:end_index]))
if self.gpoints is not None:
lp = self.interpolated[end_index - 1]
feed = self.gpoints.default_feedrate
if lp.feedrate is not None:
feed = lp.feedrate
if lp.feedrate is not None and lp.position is not None:
self.stats.setText(
"x=% 4.2f y=% 4.2f z=% 4.2f f=%i, line=%i" % (lp.position[0], lp.position[1], lp.position[2], int(feed), lp.line_number))
if self.gl_cutting_tool is not None:
self.gl_cutting_tool.resetTransform()
if lp.rotation is not None:
self.gl_cutting_tool.rotate(-lp.rotation[0], 1, 0, 0)
axis = rotate_y((0, 0, 1), lp.rotation[1]*PI/180.0)
#self.gl_cutting_tool.rotate(lp.rotation[2], 0, 1, 0)
self.gl_cutting_tool.rotate(-lp.rotation[2], axis[0], axis[1], axis[2])
#self.gl_cutting_tool.rotate(2*lp.rotation[1], 0, 1, 0)
self.gl_cutting_tool.translate(lp.position[0], lp.position[1], lp.position[2])
else:
self.gl_cutting_tool.translate(lp.position[0], lp.position[1], lp.position[2])
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,324 | codemakeshare/g-mint | refs/heads/master | /tools/threading_tool.py | from guifw.abstractparameters import *
from gcode import *
from collections import OrderedDict
class ThreadingTool(ItemWithParameters):
def __init__(self, path=[], model=None, tools=[], viewUpdater=None, **kwargs):
ItemWithParameters.__init__(self, **kwargs)
self.model = None #threading tool doesn't have a model
self.viewUpdater = viewUpdater
self.path = GCode()
self.millingDirection = ChoiceParameter(parent=self, name="Milling direction", choices=["CW top-down (RH)", "CCW bottom-up (RH)", "CCW top-down (LH)", "CW bottom-up (LH)"], value="CW top-down (RH)", callback = self.generatePath)
self.presets = OrderedDict([("M3",[3, 0.5, 0, 2.0]),
("M4",[4, 0.7, 0, 2.0]),
("M5",[5, 0.8, 0, 4.0]),
("M6",[6, 1, 0, 4.0]),
("M8",[8, 1.25, 0, 4.0]),
("M10",[10, 1.5, 0, 4.0]),
("NPT 1/8",[0.38*25.4, 1.0/27.0*25.4, 1.7899, 4.0]),
("NPT 1/4", [13.6, 1.0 / 18.0 * 25.4, 1.7899, 4.0])])
self.tool =ChoiceParameter(parent=self, name="Tool", choices=tools, value=tools[0])
self.presetParameter = ChoiceParameter(parent=self, name="Presets", choices=self.presets.keys(), value = "M6", callback = self.loadPreset)
self.startDepth=NumericalParameter(parent=self, name='start depth', value=0, enforceRange=False, step=0.1, callback = self.generatePath)
self.stopDepth=NumericalParameter(parent=self, name='end depth ', value=-10, enforceRange=False, step=0.1, callback = self.generatePath)
self.xpos = NumericalParameter(parent=self, name='x ', value=0, min=-2000, max=2000, enforceRange=False, step=0.1, callback = self.generatePath)
self.ypos = NumericalParameter(parent=self, name='y ', value=0, min=-2000, max=2000, enforceRange=False, step=0.1, callback = self.generatePath)
self.startDiameter = NumericalParameter(parent=self, name='start diameter ', value=8, min=0, max=100, enforceRange=False, step=0.1, callback = self.generatePath)
self.diameter = NumericalParameter(parent=self, name='final diameter ', value=8, min=0, max=100, enforceRange=False, step=0.01, callback = self.generatePath)
self.diameterSteps = NumericalParameter(parent=self, name='diameter steps ', value=0, min=0, max=10, step=1, callback = self.generatePath)
self.pitch=NumericalParameter(parent=self, name='thread pitch', value=1.0, min=0.01, max=5, step=0.01, callback = self.generatePath)
self.toolDiameter=NumericalParameter(parent=self, name='tool tip diameter', value=4.0, min=0, max=20, step=0.01, callback = self.generatePath)
self.coneAngle=NumericalParameter(parent=self, name='cone angle', value=0.0, min=-89.9, max=89.9, step=0.01, callback = self.generatePath)
self.backoffPercentage=NumericalParameter(parent=self, name='backoff percentage', value=100.0, min=-30, max=100, enforceRange=False, step=5, callback = self.generatePath)
self.traverseHeight=NumericalParameter(parent=self, name='traverse height', value=5.0, enforceRange=False, step=1.0, callback = self.generatePath)
self.filename=TextParameter(parent=self, name="output filename", value="thread.ngc")
self.saveButton=ActionParameter(parent=self, name='Save to file', callback=self.save)
self.feedrate=NumericalParameter(parent=self, name='default feedrate', value=400.0, min=1, max=5000, step=10)
self.parameters=[self.tool, self.millingDirection, self.presetParameter, [ self.xpos, self.ypos], self.startDepth, self.stopDepth, self.startDiameter, self.diameter, self.diameterSteps, self.pitch, self.toolDiameter, self.coneAngle, self.backoffPercentage, self.traverseHeight, self.feedrate, [self.filename, self.saveButton] ]
self.generatePath(None)
def setThread(self, diameter, pitch, angle, tool):
self.diameter.updateValue(diameter)
#self.diameter.viewRefresh()
self.pitch.updateValue(pitch)
#self.pitch.viewRefresh()
self.coneAngle.updateValue(angle)
#self.coneAngle.viewRefresh()
self.toolDiameter.updateValue(tool)
#self.toolDiameter.viewRefresh()
self.generatePath(None)
def loadPreset(self, parameter):
params = self.presets[parameter.value]
self.setThread(*params)
def generatePath(self, parameter):
self.path.outpaths=[]
path = []
self.path.path=[]
self.patterns=[]
cx=self.xpos.getValue()
cy=self.ypos.getValue()
pos = [cx, cy, 0]
start_depth = self.startDepth.getValue()
final_depth = self.stopDepth.getValue()
stepdown = self.pitch.getValue()
tool_radius = self.toolDiameter.getValue()/2.0
traverse_height=self.traverseHeight.getValue()
backoff_percentage=self.backoffPercentage.getValue()/100.0
hole_diameter = self.diameter.getValue()
hole_radius=self.startDiameter.getValue()/2.0
if self.diameterSteps.getValue()==0:
hole_radius = hole_diameter/2.0
cone_angle = self.coneAngle.getValue()/180.0*PI
angle_steps=200
lefthand = self.millingDirection.getValue() in [ "CCW top-down (LH)", "CW bottom-up (LH)"]
bottomup = self.millingDirection.getValue() in ["CCW bottom-up (RH)", "CW bottom-up (LH)"]
for cycles in range(0, int(self.diameterSteps.getValue())+1):
d=start_depth
x=pos[0]; y=pos[1]+hole_radius-tool_radius; z=0.0;
x=(1.0-backoff_percentage)*x + backoff_percentage*pos[0]
y=(1.0-backoff_percentage)*y + backoff_percentage*pos[1]
path.append(GPoint(position=([x, y, traverse_height]), rapid=True))
z=start_depth
path.append(GPoint(position=([x,y,z])))
while d>final_depth:
for i in range(0,angle_steps+1):
if d>final_depth:
d-=stepdown/angle_steps
else:
d=final_depth
break
x=pos[0]+ (hole_radius-tool_radius+(d-start_depth)*sin(cone_angle)/cos(cone_angle)) *sin((float(i)/angle_steps)*2*PI)
y=pos[1]+ (hole_radius-tool_radius+(d-start_depth)*sin(cone_angle)/cos(cone_angle)) *cos((float(i)/angle_steps)*2*PI)
z=d
if lefthand:
x=-x
path.append(GPoint(position=([x,y,z])))
# for i in range(0,angle_steps+1):
# if d>final_depth:
# d-=stepdown/angle_steps
# else:
# d=final_depth
# x=pos[0]+ (hole_radius-tool_radius+(d-start_depth)*sin(cone_angle)) *sin((float(i)/angle_steps)*2*PI)
# y=pos[1]+ (hole_radius-tool_radius+(d-start_depth)*sin(cone_angle)) *cos((float(i)/angle_steps)*2*PI)
# z=d
# path.append([x,y,z])
x=(1.0-backoff_percentage)*x + backoff_percentage*pos[0]
y=(1.0-backoff_percentage)*y + backoff_percentage*pos[1]
#z=(1.0-backoff_percentage)*z + backoff_percentage*traverse_height
path.append(GPoint(position=([x,y,z])))
path.append(GPoint(position=([x,y,traverse_height]), rapid=True))
if bottomup:
path.reverse()
self.path.path += path
path = []
if self.diameterSteps.getValue()>0:
hole_radius+=(hole_diameter-self.startDiameter.getValue())/self.diameterSteps.getValue() / 2.0
if cycles == int(self.diameterSteps.getValue()):
hole_radius = hole_diameter/2.0
if self.viewUpdater!=None:
print("updating view")
self.viewUpdater(self.path)
def save(self):
self.path.default_feedrate=self.feedrate.getValue()
self.path.write(self.filename.getValue())
def calcPath(self):
return self.path
def getCompletePath(self):
return self.calcPath()
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,325 | codemakeshare/g-mint | refs/heads/master | /geometry_tests.py | from geometry import *
def testCircleIntersection():
a=[-2, 0.5]
b=[2, 0.5]
p=[0, 0]
radius=1.0
print sign(0), sign(-1), sign(1)
ip = intersectLineOriginCircle2D(a, b, radius)
print ip
testCircleIntersection()
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,326 | codemakeshare/g-mint | refs/heads/master | /gui.py | from PyQt4.QtCore import *
from PyQt4 import QtGui
from tools import *
from tools.modeltool import *
from tools.tool import *
from tools.milltask import *
import pyqtgraph.opengl as gl
import pyqtgraph as pg
from solids import *
import sys
from gui_elements import *
from modeldialog import *
from pathdialog import *
from taskdialog import *
from grbldialog import *
class CAMGui(QtGui.QSplitter):
def __init__(self):
QtGui.QSplitter.__init__(self)
self.tabs=QtGui.QTabWidget()
self.modeltab=ModelDialog()
self.tabs.addTab(self.modeltab, "Model")
self.tooltab=ListWidget(itemlist=[Tool()], title="Tools", itemclass=Tool, name="Cutter")
self.tabs.addTab(self.tooltab, "Tools")
self.availablePathTools = OrderedDict([("Load GCode", PathTool), ("Thread milling", threading_tool.ThreadingTool)])
#itemlist=[threading_tool.ThreadingTool(viewUpdater=self.modeltab.viewer.showPath)]
#self.pathtab=ListWidget(itemlist=[], title="Paths", itemclass=self.availablePathTools, on_select_cb=self.display_path, viewUpdater=self.modeltab.viewer.showPath)
self.pathtab = PathDialog(modelmanager=self.modeltab, tools=self.tooltab.listmodel.listdata)
self.milltab=TaskDialog(modelmanager=self.modeltab, tools=self.tooltab.listmodel.listdata, path_output=self.pathtab.pathtab)
self.grbltab = GrblDialog(path_dialog=self.pathtab)
self.tabs.addTab(self.milltab, "Milling tasks")
self.tabs.addTab(self.pathtab, "Path tools")
self.tabs.addTab(self.grbltab, "Machine")
#self.w=self.tabs
self.addWidget(self.tabs)
self.addWidget(self.modeltab.viewer)
self.setWindowTitle('minCAM')
self.updateGeometry()
self.resize(1600, 900)
## Display the widget as a new window
app = QtGui.QApplication([])
camgui=CAMGui()
camgui.show()
## Start the Qt event loop
app.exec_()
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,327 | codemakeshare/g-mint | refs/heads/master | /polygons.py |
import pyclipper
from gcode import *
from scipy.spatial import Voronoi
class PolygonGroup:
def __init__(self, polys = None, precision = 0.005, scaling = 1000.0, zlevel = 0):
if polys is None:
self.polygons=[]
else:
self.polygons = polys
self.scaling = scaling
self.precision = precision
self.zlevel = zlevel
def addPolygon(self, points):
self.polygons.append(points)
# determine if a point is inside this polygon
def pointInside(self, p):
x=p[0]
y=p[1]
inside =False
for poly in self.polygons:
n = len(poly)
p1x,p1y = poly[0][0:2]
for i in range(n+1):
p2x,p2y = poly[i % n][0:2]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xinters = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xinters:
inside = not inside
p1x,p1y = p2x,p2y
return inside
def getBoundingBox(self):
points = [p for poly in self.polygons for p in poly]
return polygon_bounding_box(points)
def translate(self, v):
for poly in self.polygons:
for p in poly:
p[0]+=v[0]
p[1] += v[1]
p[2] += v[2]
def interpolateLines(self, maxLength):
ipolys=[]
for poly in self.polygons:
newpoly=[]
for i in range(0, len(poly)):
line=([poly[i], poly[(i+1)%len(poly)]])
length = dist(line[0], line[1])
if length > maxLength:
vec = [line[1][k]-line[0][k] for k in range(0, len(line[0]))]
isegments = int(length/(maxLength))+1
newpoly.append(poly[i])
for j in range(0, isegments-1):
newpoly.append([line[0][k]+j*vec[k]/isegments for k in range(0, len(line[0]))])
else:
newpoly.append(poly[i])
ipolys.append(newpoly)
return ipolys
def medialLines(self):
points=[]
ipolys = self.interpolateLines(2.0)
for poly in ipolys:
points+=[[p[0], p[1]] for p in poly]
if len(points)<3:
return []
vor = Voronoi(points)
vpoints = [[p[0], p[1], self.zlevel] for p in vor.vertices]
segments = []
for r in vor.ridge_vertices:
if r[0]>=0 and r[1]>=0 and self.pointInside(vpoints[r[0]]) and self.pointInside(vpoints[r[1]]):
segments.append([r[0], r[1]])
outpaths = [[vpoints[i] for i in s]for s in segments]
cleanPaths = PolygonGroup(polys=outpaths, precision=0.5, zlevel=self.zlevel)
#cleanPaths.joinConnectedLines()
return cleanPaths
def joinConnectedLines(self):
finished = False
while not finished:
finished = True
for i in range(0, len(self.polygons)):
poly=self.polygons[i]
if len(poly)==0:
del self.polygons[i]
finished=False
break
if len(poly)==1: # for stray points, check if they are already contained somewhere
contained = False
for j in range(0, len(self.polygons)):
if i!=j:
s = self.polygons[j]
for p in s:
if dist(poly[0], p)<self.precision:
contained=True
break
if contained:
break
if contained:
del self.polygons[i]
finished=False
break
if not finished:
break
# see if this fits any existing segment:
inserted=False
for j in range(i+1, len(self.polygons)):
inserted=False
s = self.polygons[j]
if dist(poly[0], s[0])<self.precision:
for p in s[1:]:
poly.insert(0, p)
inserted=True
elif dist(poly[0], s[-1])<self.precision:
for p in reversed(s[:-1]):
poly.insert(0, p)
inserted=True
elif dist(poly[-1], s[0])<self.precision:
for p in (s[1:]):
poly.append(p)
inserted=True
elif dist(poly[-1], s[-1])<self.precision:
for p in reversed(s[:-1]):
poly.append(p)
inserted=True
if inserted:
del self.polygons[j]
finished=False
break
if not finished:
break
# we're only done if we can't do any more joining
#remove overlapping line segments
for poly in self.polygons:
if len(poly)>=2:
closest_distance, closest_point, closest_index = closest_point_on_open_polygon(poly[0], poly[1:])
if closest_distance <self.precision:
#remove overlapping point
del poly[0]
finished=False
break
if len(poly)>=2:
closest_distance, closest_point, closest_index = closest_point_on_open_polygon(poly[-1], poly[:-1])
if closest_distance <self.precision:
#remove overlapping point
del poly[-1]
finished = False
break
#delete any stray lines left after joining
#for i in reversed(range(0, len(self.polygons))):
# poly=self.polygons[i]
# if len(poly)==2:
# del self.polygons[i]
#check for joints and split segments at the joint
finished=False
while not finished:
finished=True
for i in range(0, len(self.polygons)):
for j in range(0, len(self.polygons)):
if i!=j and len(self.polygons[i])>2:
for k in range(1, len(self.polygons[i])-1): # go through all points except start and end
if dist(self.polygons[i][k], self.polygons[j][0]) < self.precision or dist(self.polygons[i][k], self.polygons[j][-1]) < self.precision:
#split poly
segment1 = [p for p in self.polygons[i][:k+1]] #include joint point
segment2 = [p for p in self.polygons[i][k:]]
del self.polygons[i]
self.polygons.append(segment1)
self.polygons.append(segment2)
finished = False
break
if not finished:
break
if not finished:
break
finished=False
while not finished:
finished=True
for i in range(0, len(self.polygons)):
if len(self.polygons[i])==2 and dist(self.polygons[i][0], self.polygons[i][1])<self.precision:
del self.polygons[i]
finished=False
break
def medialLines2(self):
lines = []
for poly in self.polygons:
for i in range(0, len(poly)):
lines.append([poly[i], poly[(i+1)%len(poly)]])
segments = []
for i in range(0, len(lines)):
for j in range(i, len(lines)):
l1= lines[i]
l2=lines[j]
angle = full_angle2d([l1[0][0]-l2[1][0], l1[0][1]-l2[1][1]], [l1[1][0]-l2[0][0], l1[1][1]-l2[0][1]])
#if angle>PI:
m1 = [(l1[0][0]+l2[1][0])/2, (l1[0][1]+l2[1][1])/2, self.zlevel]
m2 = [(l1[1][0]+l2[0][0])/2, (l1[1][1]+l2[0][1])/2, self.zlevel]
segments.append([m1, m2])
return segments
def offset(self, radius=0, rounding = 0.0):
offset=[]
clip = pyclipper.PyclipperOffset() #Pyclipper
polyclipper = pyclipper.Pyclipper() #Pyclipper
for pat in self.polygons:
outPoly=[[int(self.scaling*p[0]), int(self.scaling*p[1])] for p in pat] #Pyclipper
outPoly = pyclipper.SimplifyPolygons([outPoly])
try:
polyclipper.AddPaths(outPoly, poly_type=pyclipper.PT_SUBJECT, closed=True)
except:
None
#print "path invalid", outPoly
poly = polyclipper.Execute(pyclipper.CT_UNION, pyclipper.PFT_EVENODD, pyclipper.PFT_EVENODD)
clip.AddPaths(poly, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON)
offset = clip.Execute( -int((radius+rounding)*self.scaling))
offset = pyclipper.SimplifyPolygons(offset)
if rounding>0.0:
roundclipper = pyclipper.PyclipperOffset()
roundclipper.AddPaths(offset, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON)
offset = roundclipper.Execute( int(rounding*self.scaling))
offset = pyclipper.CleanPolygons(offset, distance=self.scaling*self.precision)
#print (len(offset))
result = PolygonGroup(scaling = self.scaling, precision = self.precision, zlevel = self.zlevel)
result.polygons = []
for poly in offset:
if len(poly)>0:
output_poly = [[float(x[0])/self.scaling, float(x[1])/self.scaling, self.zlevel] for x in poly]
result.addPolygon(output_poly)
return result
def convolute(self, pattern):
spoly=[]
for pat in self.polygons:
spoly.append([[int(self.scaling*p[0]), int(self.scaling*p[1])] for p in pat]) #Pyclipper
spattern = [[int(self.scaling*p[0]), int(self.scaling*p[1])] for p in pattern]
output = pyclipper.MinkowskiSum2(spattern, spoly, True)
result = PolygonGroup(scaling = self.scaling, precision = self.precision, zlevel = self.zlevel)
result.polygons = []
for poly in output:
if len(poly)>0:
output_poly = [[float(x[0])/self.scaling, float(x[1])/self.scaling, self.zlevel] for x in poly]
result.addPolygon(output_poly)
return result
def trim(self, trimPoly):
if len(self.polygons)>0 and len(trimPoly.polygons)>0:
polytrim = pyclipper.Pyclipper() #Pyclipper
polytrim.AddPaths([[[int(self.scaling*p[0]), int(self.scaling*p[1])] for p in pat] for pat in trimPoly.polygons], poly_type=pyclipper.PT_CLIP, closed=True)
polytrim.AddPaths([[[int(self.scaling*p[0]), int(self.scaling*p[1])] for p in pat] for pat in self.polygons], poly_type=pyclipper.PT_SUBJECT, closed=True)
try:
trimmed = polytrim.Execute(pyclipper.CT_INTERSECTION, pyclipper.PFT_EVENODD, pyclipper.PFT_EVENODD)
trimmed = pyclipper.SimplifyPolygons(trimmed)
self.polygons = [[[float(x[0])/self.scaling, float(x[1])/self.scaling, self.zlevel] for x in poly] for poly in trimmed]
except:
print("clipping intersection error")
#remove all points outside of trimPoly
def clip(self, trim_poly):
clipped_polys=[]
if len(self.polygons) > 0 and len(trim_poly.polygons) > 0:
clipped_poly=[]
for poly in self.polygons:
clipped_poly=[]
for p in poly:
if trim_poly.pointInside(p):
clipped_poly.append(p)
else: # if point outside, flush collected points and start new segment
if len(clipped_poly) > 0:
clipped_polys.append(clipped_poly)
clipped_poly=[]
if len(clipped_poly)>0:
clipped_polys.append(clipped_poly)
self.polygons=clipped_polys
def clipToBoundingBox(self, minx, miny, maxx, maxy):
clipped_polys=[]
if len(self.polygons) > 0:
clipped_poly=[]
for poly in self.polygons:
clipped_poly=[p for p in poly if p[0]>minx and p[0]<maxx and p[1]>miny and p[1]<maxy]
if len(clipped_poly)>0:
clipped_polys.append(clipped_poly)
self.polygons=clipped_polys
def trimToBoundingBox(self, minx, miny, maxx, maxy):
clipped_polys=[]
trimPoly = PolygonGroup([[[minx, miny], [minx, maxy], [maxx, maxy], [maxx, miny]]])
self.trim(trimPoly)
def compare(self, reference, tolerance=0.01):
for poly in self.polygons:
for p in poly:
found = False
for r in reference.polygons:
bdist, bpoint, bindex = closest_point_on_polygon(p, r)
if bdist<tolerance: # found a point that is within tolerance
found=True
break
if not found: # if we could not find a point within tolerance, abort
return False
return True
def pointDistance(self, p):
dist = None
cp = None
ci=None
subpoly = None
for poly in self.polygons:
pdist, pcp, pindex =closest_point_on_polygon(p, poly)
if dist is None or pdist<dist:
dist = pdist
cp = pcp
subpoly = poly
ci=pindex
return dist, cp, subpoly, ci
def intersectWithLine(self, a, b):
if len(self.polygons) > 0:
points = []
for poly in self.polygons:
points+=intersectLinePolygon(a, b, poly)
points.sort(key=lambda p: dist(p, a))
return points
else:
return []
def drapeCover(self, a, b):
if len(self.polygons) > 0:
points = []
for poly in self.polygons:
points+=intersectLinePolygonBracketed(a, b, poly)
points.sort(key=lambda e: dist(e[0], a))
return points
else:
return []
#compares polygon to a reference polygon and returns a set of subpaths that differ from the reference
def getDifferentPathlets(self, reference, tolerance=0.01):
result = PolygonGroup(scaling = self.scaling, precision = self.precision, zlevel = self.zlevel)
result.polygons=[]
subpoly=[]
for poly in self.polygons:
for p in poly+[poly[0]]:
found = False
for r in reference.polygons:
bdist, bpoint, bindex = closest_point_on_polygon(p, r)
if bdist<tolerance: # found a point that is within tolerance
found=True
break
if not found: # if we could not find a point within tolerance, abort
subpoly.append(p)
else:
if len(subpoly)>0:
result.polygons.append(subpoly)
subpoly=[]
return result
class polygon_tree:
def __init__(self, path=None):
self.path = path
self.parent = None
self.children = []
self.topDownOrder = 0
self.bottomUpOrder = 0
def insert(self, new_path):
if len(new_path) == 0: # empty poly - ignore
return
if self.parent is None:
print("adding path", polygon_chirality(new_path))
if len(self.children) < 2:
self.children = [polygon_tree(), polygon_tree()]
self.children[0].parent = self
self.children[1].parent = self
print("top level:", len(self.children))
if polygon_chirality(new_path) < 0:
self.children[0].insert(new_path)
else:
self.children[1].insert(new_path)
return
if self.path is None:
self.path = new_path
return
if (new_path[0][2] == self.path[0][2] and polygons_nested(new_path, self.path)):
print("fits into me")
# check which sub-branch to go down
for child in self.children:
if new_path[0][2] == child.path[0][2] and polygons_nested(new_path, child.path):
child.insert(new_path)
return
# path fits into this node, but none of its children - add to list of children
# find all children contained by new node
node = polygon_tree(new_path)
for child in self.children:
if new_path[0][2] == child.path[0][2] and polygons_nested(child.path, new_path):
print("push down to child")
# shift child into subtree of node
self.children.remove(child)
node.children.append(child)
child.parent = node
# insert new node sorted by z height
pos = 0
while pos < len(self.children) - 1 and self.children[pos].path[0][2] > node.path[0][2]:
pos += 1
self.children.insert(pos, node)
node.parent = self
else:
if (new_path[0][2] == self.path[0][2] and polygons_nested(self.path, new_path)):
print("I fit into it")
# if path doesn't fit into this node, shift this node into new subtree
tmp = polygon_tree(self.path)
tmp.parent = self
tmp.children = self.children
self.children = [tmp]
self.path = new_path
else:
print("path doesn't fit anywhere!")
inserted = False
if self.parent is not None:
for child in self.parent.children:
if child is not None and child.path is not None and new_path[0][2] == child.path[0][2] and polygons_nested(child.path, new_path):
print("push down to child")
inserted = True
child.insert(new_path)
if not inserted:
print("create new parallel path")
self.parent.children.append(polygon_tree(new_path))
def pathLength(self):
lastp = array(self.path[0])
length = 0
for p in self.path:
s_length = norm(array(p) - lastp)
lastp = array(p)
length += s_length
return length
def getShortestSubpathLength(self):
shortest = self.pathLength()
for c in self.children:
sublength = c.getShortestSubpathLength()
if sublength < shortest:
shortest = sublength
return shortest
def toList(self):
result = []
for child in self.children:
for sc in child.toList():
result.append(sc)
if self.path is not None:
result.append(self.path)
return result
def calcOrder(self):
if self.parent is None:
self.topDownOrder = 0
else:
self.topDownOrder = self.parent.topDownOrder + 1
if len(self.children) == 0:
self.bottumUpOrder = 0
else:
for child in self.children:
child.calcOrder()
self.bottomUpOrder = max(self.bottomUpOrder, child.bottomUpOrder + 1)
def toGPoints(self):
self.calcOrder()
result = []
for child in self.children:
for sc in child.toGPoints():
result.append(sc)
lastpoint = None
if len(result) > 0:
lastpoint = result[-1][-1]
if self.path is not None:
closest_point_index = 0
if lastpoint is not None:
for i in range(0, len(self.path)):
if dist(lastpoint.position, self.path[i]) < dist(lastpoint.position, self.path[closest_point_index]):
closest_point_index = i
opt_path = self.path[closest_point_index:] + self.path[:closest_point_index]
order = self.bottomUpOrder
out_poly = [GPoint(position=(p[0], p[1], p[2]), order=order, dist_from_model=self.topDownOrder) for p in opt_path]
# explicitly close path
out_poly.append(out_poly[0])
result.append(out_poly)
return result
def toGPointsOutIn(self):
self.calcOrder()
result = []
lastpoint = None
if len(result) > 0:
lastpoint = result[-1][-1]
if self.path is not None:
closest_point_index = 0
if lastpoint is not None:
for i in range(0, len(self.path)):
if dist(lastpoint.position, self.path[i]) < dist(lastpoint.position, self.path[closest_point_index]):
closest_point_index = i
opt_path = self.path[closest_point_index:] + self.path[:closest_point_index]
order = self.bottomUpOrder
result.append([GPoint(position=(p[0], p[1], p[2]), order=order, dist_from_model=self.topDownOrder) for p in opt_path])
for child in self.children:
for sc in child.toGPointsOutIn():
result.append(sc)
return result
def optimise(self):
if len(self.children) == 0:
return
for c in self.children:
c.optimise()
if self.parent is None:
return
# check if all children are on same depth
for c in self.children:
if c.path is not None and c.path[0][2] != self.children[0].path[0][2]:
print("not on same depth")
return
# reorder children
optimisedList = [self.children[0]]
del self.children[0]
while len(self.children) > 0:
# find closest path to last one:
ci = 0
p1 = optimisedList[-1].path[0]
for i in range(0, len(self.children)):
# for p1 in optimisedList[-1].path:
if dist(p1, self.children[i].path[0]) < dist(p1, self.children[ci].path[0]):
ci = i
optimisedList.append(self.children[ci])
del self.children[ci]
self.children = optimisedList | {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,328 | codemakeshare/g-mint | refs/heads/master | /OrthoGLViewWidget.py | from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph.opengl as gl
from OpenGL.GL import *
import numpy as np
from pyqtgraph import Vector
##Vector = QtGui.QVector3D
class OrthoGLViewWidget(gl.GLViewWidget):
def __init__(self, parent=None):
gl.GLViewWidget.__init__(self, parent)
self.opts["azimuth"]=-90
self.opts["elevation"] = 90
self.opts["tilt"] = 0
self.setOrthoProjection()
def setProjection(self, region=None):
if self.opts['ortho_projection']:
m = self.projectionMatrixOrtho(region)
else:
m = self.projectionMatrix(region)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
a = np.array(m.copyDataTo()).reshape((4,4))
glMultMatrixf(a.transpose())
def projectionMatrixOrtho(self, region=None):
# Xw = (Xnd + 1) * width/2 + X
if region is None:
region = (0, 0, self.width(), self.height())
x0, y0, w, h = self.getViewport()
dist = self.opts['distance']
fov = self.opts['fov']
nearClip = dist * 0.001
farClip = dist * 1000.
r = nearClip * np.tan(fov * 0.5 * np.pi / 180.)
t = r * h / w
# convert screen coordinates (region) to normalized device coordinates
# Xnd = (Xw - X0) * 2/width - 1
## Note that X0 and width in these equations must be the values used in viewport
left = r * ((region[0]-x0) * (2.0/w) - 1)
right = r * ((region[0]+region[2]-x0) * (2.0/w) - 1)
bottom = t * ((region[1]-y0) * (2.0/h) - 1)
top = t * ((region[1]+region[3]-y0) * (2.0/h) - 1)
tr = QtGui.QMatrix4x4()
scale=500.0
tr.ortho(-scale*r, scale* r, -scale*t, scale*t, nearClip, farClip)
tr.rotate(self.opts["tilt"],0.0,0.0,1.0)
return tr
def setOrthoProjection(self):
self.opts['ortho_projection']=True
def setPerspectiveProjection(self):
self.opts['ortho_projection']=False
def pan(self, dx, dy, dz, relative=False):
"""
Moves the center (look-at) position while holding the camera in place.
If relative=True, then the coordinates are interpreted such that x
if in the global xy plane and points to the right side of the view, y is
in the global xy plane and orthogonal to x, and z points in the global z
direction. Distances are scaled roughly such that a value of 1.0 moves
by one pixel on screen.
"""
if not relative:
self.opts['center'] += QtGui.QVector3D(dx, dy, dz)
else:
cPos = self.cameraPosition()
cVec = self.opts['center'] - cPos
dist = cVec.length() ## distance from camera to center
xDist = dist * 1. * np.tan(
0.5 * self.opts['fov'] * np.pi / 180.) ## approx. width of view at distance of center point
xScale = xDist / self.width()
azim = -self.opts['azimuth'] * np.pi / 180.
zVec = QtGui.QVector3D(0, 0, 1)
xVec = QtGui.QVector3D.crossProduct(zVec, cVec).normalized()
yVec = QtGui.QVector3D.crossProduct(cVec, xVec).normalized()
if xVec==QtGui.QVector3D(0,0,0):
xVec=QtGui.QVector3D(-np.sin(azim), -np.cos(azim), 0)
if yVec == QtGui.QVector3D(0, 0, 0):
yVec=QtGui.QVector3D(-np.cos(azim), np.sin(azim), 0)
if self.opts["elevation"]<0:
yVec=-yVec
tr = QtGui.QMatrix4x4()
tr.rotate(self.opts["tilt"], cVec)
self.opts['center'] = self.opts['center'] + tr*xVec * xScale * dx + tr*yVec * xScale * dy + tr*zVec * \
xScale * dz
self.update()
def orbit(self, azim, elev):
tilt = self.opts['tilt'] * np.pi / 180.
"""Orbits the camera around the center position. *azim* and *elev* are given in degrees."""
self.opts['azimuth'] += np.cos(tilt)*azim+np.sin(tilt)*elev
#self.opts['elevation'] += elev
self.opts['elevation'] = np.clip(self.opts['elevation'] + np.cos(tilt)*elev-np.sin(tilt)*azim, -90, 90)
self.update()
def mouseMoveEvent(self, ev):
diff = ev.pos() - self.mousePos
self.mousePos = ev.pos()
if ev.buttons() == QtCore.Qt.RightButton:
self.orbit(-diff.x(), diff.y())
# print self.opts['azimuth'], self.opts['elevation']
elif ev.buttons() == QtCore.Qt.LeftButton:
if (ev.modifiers() & QtCore.Qt.ControlModifier):
self.pan(diff.x()*self.devicePixelRatio(), 0, diff.y()*self.devicePixelRatio(), relative=True)
else:
self.pan(diff.x()*self.devicePixelRatio(), diff.y()*self.devicePixelRatio(), 0, relative=True)
elif ev.buttons() == QtCore.Qt.MidButton:
self.opts["tilt"]+=diff.x()
self.update()
def width(self):
return super().width() * self.devicePixelRatio()
def height(self):
return super().height() * self.devicePixelRatio()
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,329 | codemakeshare/g-mint | refs/heads/master | /tools/milltask.py | from guifw.abstractparameters import *
from geometry import *
from solids import *
import multiprocessing as mp
import time
import pyclipper
from polygons import *
from gcode import *
class CalcJob:
def __init__(self, function, **fargs):
self.function=function
self.fargs=fargs
def process(self):
print("running job")
return self.function(**self.fargs)
def run(pattern):
task=run.task
tool=run.task.tool.getValue()
task.model.waterlevel=task.waterlevel.value
pathlet=task.model.follow_surface(trace_path=pattern, \
traverse_height=task.traverseHeight.value,\
max_depth=task.model.minv[2], \
tool_diameter=tool.diameter.value, \
height_function=tool.getHeightFunction(task.model), \
deviation=task.deviation.value, \
margin=task.offset.value, \
min_stepx=task.minStep.value \
)
return pathlet
def run_init(task_options):
run.task=task_options
class MillTask(ItemWithParameters):
def __init__(self, model=None, tools=[], viewUpdater=None, **kwargs):
ItemWithParameters.__init__(self, **kwargs)
self.model = None
self.model_top = 0
self.model_bottom=0
if model is not None:
self.model=model.object
self.model_top = self.model.maxv[2]
self.model_bottom = self.model.minv[2]
self.patterns=[]
self.path=None
selectedTool = None
if len(tools)>0:
selectedTool = tools[0]
self.tool = ChoiceParameter(parent=self, name="Tool", choices=tools, value=selectedTool)
self.padding=NumericalParameter(parent=self, name="padding", value=0.0, step=0.1)
self.traverseHeight=NumericalParameter(parent=self, name='traverse height', value=self.model_top+10, min=self.model_bottom-100, max=self.model_top+100, step=1.0)
self.offset=NumericalParameter(parent=self, name='offset', value=0.0, min=-100, max=100, step=0.01)
self.waterlevel=NumericalParameter(parent=self, name='waterlevel', value=self.model_bottom, min=self.model_bottom, max=self.model_top, step=1.0)
self.deviation = NumericalParameter(parent=self, name='max. deviation', value=0.1, min=0.0, max=10, step=0.01)
self.minStep=NumericalParameter(parent=self, name="min. step size", value=0.1, min=0.0, max=50.0, step=0.01)
self.viewUpdater=viewUpdater
def dropPathToModel(self):
tool_diameter = self.tool.getValue().diameter.value
keepToolDown = False
patterns = self.patterns
self.model.__class__ = CAM_Solid
self.model.calc_ref_map(tool_diameter / 2.0, tool_diameter / 2.0 + self.offset.value)
pool = mp.Pool(None, run_init, [self])
mresults = pool.map_async(run, patterns)
remaining = 0
while not (mresults.ready()):
if mresults._number_left != remaining:
remaining = mresults._number_left
print("Waiting for", remaining, "tasks to complete...")
time.sleep(1)
pool.close()
pool.join()
results = mresults.get()
# run_init(self)
# results=map(run, self.patterns)
self.path = GCode()
self.path.append(
GPoint(position=(results[0][0].position[0], results[0][0].position[1], self.traverseHeight.value),
rapid=True))
for segment in results:
# self.path+=p
if not keepToolDown:
self.path.append(
GPoint(position=(segment[0].position[0], segment[0].position[1], self.traverseHeight.value),
rapid=True))
for p in segment:
self.path.append(p)
if not keepToolDown:
self.path.append(
GPoint(position=(segment[-1].position[0], segment[-1].position[1], self.traverseHeight.value),
rapid=True))
self.path.append(
GPoint(position=(results[-1][-1].position[0], results[-1][-1].position[1], self.traverseHeight.value),
rapid=True))
# self.path=self.model.follow_surface(trace_path=self.pattern, traverse_height=self.traverseHeight.value, max_depth=self.model.minv[2], tool_diameter=6, height_function=self.model.get_height_ball_geometric, deviation=0.5, min_stepx=0.2, plunge_ratio=0.0)
return self.path
class PatternTask(MillTask):
def __init__(self, model=None, tools=[], **kwargs):
MillTask.__init__(self, model, tools, **kwargs)
self.direction=ChoiceParameter(parent=self, name="Pattern direction", choices=["X", "Y", "Spiral", "Concentric"], value="X")
self.model=model.object
self.forwardStep=NumericalParameter(parent=self, name="forward step", value=3.0, min=0.0001, step=0.1)
self.sideStep=NumericalParameter(parent=self, name="side step", value=1.0, min=0.0001, step=0.1)
self.sliceIter=NumericalParameter(parent=self, name="iterations", value=0, step=1, enforceRange=False, enforceStep=True)
#self.diameter=NumericalParameter(parent=self, name="tool diameter", value=6.0, min=0.0, max=1000.0, step=0.1)
self.parameters=[self.tool, self.padding, self.direction, self.forwardStep, self.sideStep, self.traverseHeight, self.waterlevel, self.minStep, self.offset, self.sliceIter, self.deviation]
self.patterns=None
def generatePattern(self):
print(self.tool.getValue().name.getValue(), self.tool.getValue().getDescription())
self.model.get_bounding_box()
#self.model.add_padding((padding,padding,0))
if self.direction.getValue()=="X":
self.generateXPattern()
if self.direction.getValue()=="Y":
self.generateYPattern()
if self.direction.getValue()=="Spiral":
self.generateSpiralPattern()
if self.direction.getValue()=="Concentric":
self.generateConcentric()
if self.direction.getValue()=="Outline":
self.generateOutline()
def generateXPattern(self):
model=self.model
#padding=self.tool.getValue().diameter.value +self.offset.value
padding = self.padding.getValue()
start_pos=[model.minv[0]-padding, model.minv[1]-padding, model.minv[2]]
end_pos=[model.maxv[0]+padding, model.maxv[1]+padding, model.maxv[2]]
stepx=self.forwardStep.value
stepy=self.sideStep.value
path=[]
#path.append(start_pos)
y=start_pos[1]
#last_pass=0
dir=1
self.patterns=[]
while y<=end_pos[1]:
if dir==1:
for x in frange(start_pos[0], end_pos[0], stepx):
path.append([x, y, self.traverseHeight.value])
x=end_pos[0]
path.append([x, y, self.traverseHeight.value])
self.patterns.append(path)
path=[]
else:
for x in frange(end_pos[0],start_pos[0], -stepx):
path.append([x, y, self.traverseHeight.value])
x=start_pos[0]
path.append([x, y, self.traverseHeight.value])
self.patterns.append(path)
path=[]
dir=-dir
if y<end_pos[1]:
y+=stepy
if y>end_pos[1]:
y=end_pos[1]
else:
y+=stepy
def generateYPattern(self):
model=self.model
start_pos=model.minv
#padding=self.tool.getValue().diameter.value +self.offset.value
padding = self.padding.getValue()
start_pos=[model.minv[0]-padding, model.minv[1]-padding, model.minv[2]]
end_pos=[model.maxv[0]+padding, model.maxv[1]+padding, model.maxv[2]]
stepy=self.forwardStep.value
stepx=self.sideStep.value
path=[]
#path.append(start_pos)
x=start_pos[0]
#last_pass=0
dir=1
self.patterns=[]
while x<=end_pos[0]:
if dir==1:
for y in frange(start_pos[1], end_pos[1], stepy):
path.append([x, y, self.traverseHeight.value])
y=end_pos[1]
path.append([x, y, self.traverseHeight.value])
self.patterns.append(path)
path=[]
else:
for y in frange(end_pos[1],start_pos[1], -stepy):
path.append([x, y, self.traverseHeight.value])
y=start_pos[1]
path.append([x, y, self.traverseHeight.value])
self.patterns.append(path)
path=[]
dir=-dir
if x<end_pos[0]:
x+=stepx
if x>end_pos[0]:
x=end_pos[0]
else:
x+=stepx
def generateSpiralPattern(self, climb=True, start_inside=True):
model=self.model
#padding=self.tool.getValue().diameter.value +self.offset.value
padding = self.padding.getValue()
bound_min=[model.minv[0]-padding, model.minv[1]-padding, model.minv[2]]
bound_max=[model.maxv[0]+padding, model.maxv[1]+padding, model.maxv[2]]
path=[]
#path.append(start_pos)
# set start position to corner
pos = [bound_min[0], bound_min[1], self.traverseHeight.value]
if (climb and start_inside) or (not climb and not start_inside) :
vec = [0, self.forwardStep.value, 0]
else:
vec = [self.forwardStep.value, 0, 0]
self.patterns=[]
firstpass=True
while bound_min[0]<bound_max[0] or bound_min[1]<bound_max[1]:
if (pos[0]>=bound_min[0] and pos[0]<=bound_max[0] and pos[1]>=bound_min[1] and pos[1]<=bound_max[1]):
path.append([pos[0], pos[1], pos[2]])
else:
# clip to bounding box
if pos[0] > bound_max[0]:
pos[0] = bound_max[0]
if not firstpass:
bound_min[0] = min(bound_max[0], bound_min[0] + self.sideStep.value)
if pos[1] > bound_max[1]:
pos[1] = bound_max[1]
if not firstpass:
bound_min[1] = min(bound_max[1], bound_min[1] + self.sideStep.value)
if pos[0] < bound_min[0]:
pos[0] = bound_min[0]
if not firstpass:
bound_max[0] = max(bound_min[0], bound_max[0] - self.sideStep.value)
if pos[1] < bound_min[1]:
pos[1] = bound_min[1]
if not firstpass:
bound_max[1] = max(bound_min[1], bound_max[1] - self.sideStep.value)
path.append([pos[0], pos[1], pos[2]])
# rotate vector
t = vec[0]
if climb:
vec[0] = vec[1]
vec[1] = -t
else:
vec[0] = -vec[1]
vec[1] = t
#append path segment to output
self.patterns.append(path)
path=[]
firstpass = False
pos[0] += vec[0]
pos[1] += vec[1]
# reverse path if starting on inside:
if start_inside:
for pat in self.patterns:
pat.reverse()
self.patterns.reverse()
def generateConcentric(self):
#model=self.model
# using the padding variable as the radius (HACK)
padding = self.padding.getValue()
stepy=self.forwardStep.value #radial step
stepx=self.sideStep.value #stepover
path=[]
self.patterns=[]
center = [0, 0, self.traverseHeight.value]
iterations = int(self.sliceIter.getValue())
start_radius = padding - iterations * stepx
if start_radius<stepx:
start_radius = stepx
iterations = int((padding-start_radius) / stepx)
for i in reversed(range(0, iterations)):
radius = padding - i*stepx
for a in range(0, int(360.0/stepy)+1):
alpha = a*stepy*PI/180.0
pos = [center[0]+radius*sin(alpha), center[1]-radius*cos(alpha), center[2]]
path.append([pos[0], pos[1], pos[2]])
#keep all circles in one path pattern
self.patterns.append(path)
def getStockPolygon(self):
bound_min==[model.minv[0]-padding, model.minv[1]-padding, model.minv[2]]
bound_max=[model.maxv[0]+padding, model.maxv[1]+padding, model.maxv[2]]
stock_contours = [[bound_min[0], bound_min[1], 0],
[bound_min[0], bound_max[1], 0],
[bound_max[0], bound_max[1], 0],
[bound_max[0], bound_min[1], 0]]
stock_poly=PolygonGroup(precision = 0.01, zlevel=sliceLevel)
stock_poly.addPolygon(stock_contours)
return stock_poly
def calcPath(self):
return self.dropPathToModel()
class SliceTask(MillTask):
def __init__(self, model=None, tools=[], **kwargs):
MillTask.__init__(self, model, tools, **kwargs)
self.model_minv = [0,0,0]
self.model_maxv = [0,0,0]
if self.model is not None:
self.model_minv = self.model.minv
self.model_maxv = self.model.maxv
self.stockMinX=NumericalParameter(parent=self, name="Min. X", value=self.model_minv[0], step=0.1)
self.stockMinY=NumericalParameter(parent=self, name="Min. Y", value=self.model_minv[1], step=0.1)
self.stockSizeX=NumericalParameter(parent=self, name="Len. X", value=self.model_maxv[0]-self.model_minv[0], step=0.1)
self.stockSizeY=NumericalParameter(parent=self, name="Len. Y", value=self.model_maxv[1]-self.model_minv[1], step=0.1)
self.operation=ChoiceParameter(parent=self, name="Operation", choices=["Slice", "Slice & Drop", "Outline", "Medial Lines"], value="Slice")
self.direction=ChoiceParameter(parent=self, name="Direction", choices=["inside out", "outside in"], value="inside out")
self.model = None
if model is not None:
self.model=model.object
self.sideStep=NumericalParameter(parent=self, name="stepover", value=1.0, min=0.0001, step=0.1)
self.radialOffset = NumericalParameter(parent=self, name='radial offset', value=0.0, min=-100, max=100, step=0.01)
#self.diameter=NumericalParameter(parent=self, name="tool diameter", value=6.0, min=0.0, max=1000.0, step=0.1)
self.pathRounding = NumericalParameter(parent=self, name='path rounding', value=0.0, min=0, max=10, step=0.01)
self.precision = NumericalParameter(parent=self, name='precision', value=0.005, min=0.001, max=1, step=0.001)
self.sliceTop=NumericalParameter(parent=self, name="Slice top", value=self.model_maxv[2], step=0.1, enforceRange=False, enforceStep=False)
self.sliceBottom=NumericalParameter(parent=self, name="bottom", value=self.model_minv[2], step=0.1, enforceRange=False, enforceStep=False)
self.sliceStep=NumericalParameter(parent=self, name="step", value=100.0, step=0.1, enforceRange=False, enforceStep=False)
self.sliceIter=NumericalParameter(parent=self, name="iterations", value=0, step=1, enforceRange=False, enforceStep=True)
self.toolSide = ChoiceParameter(parent=self, name="Tool side", choices=["external", "internal"],
value="external")
self.scalloping=NumericalParameter(parent=self, name="scalloping", value=0, step=1, enforceRange=False, enforceStep=True)
self.parameters=[self.tool, [self.stockMinX, self.stockMinY], [self.stockSizeX, self.stockSizeY], self.operation, self.direction, self.sideStep, self.traverseHeight, self.radialOffset, self.pathRounding, self.precision, self.sliceTop, self.sliceBottom, self.sliceStep, self.sliceIter, self.scalloping]
self.patterns=None
def generatePattern(self):
print(self.tool.getValue().name.getValue(), self.tool.getValue().getDescription())
self.model.get_bounding_box()
#self.model.add_padding((padding,padding,0))
if self.operation.getValue()=="Outline":
self.generateOutline()
if self.operation.getValue()=="Slice" or self.operation.getValue()=="Slice & Drop" or self.operation.value=="Medial Lines":
self.slice(addBoundingBox = False)
def getStockPolygon(self):
sliceLevel = self.sliceTop.getValue()
bound_min=[self.stockMinX.getValue(), self.stockMinY.getValue()]
bound_max=[bound_min[0]+self.stockSizeX.getValue(), bound_min[1]+ self.stockSizeY.getValue()]
stock_contours = [[bound_min[0], bound_min[1], 0],
[bound_min[0], bound_max[1], 0],
[bound_max[0], bound_max[1], 0],
[bound_max[0], bound_min[1], 0]]
stock_poly=PolygonGroup(precision = 0.01, zlevel=sliceLevel)
stock_poly.addPolygon(stock_contours)
return stock_poly
def generateOutline(self):
self.model.calc_outline()
self.patterns=[]
self.patterns.append(self.model.outline)
def slice(self, addBoundingBox = True):
sliceLevel = self.sliceTop.getValue()
self.patterns = []
while sliceLevel > self.sliceBottom.getValue():
print("slicing at ", sliceLevel)
# slice slightly above to clear flat surfaces
slice = self.model.calcSlice(sliceLevel)
for s in slice:
self.patterns.append(s)
if addBoundingBox:
# add bounding box
bound_min=[self.stockMinX.getValue(), self.stockMinY.getValue()]
bound_max=[bound_min[0]+self.stockSizeX.getValue(), bound_min[1]+ self.stockSizeY.getValue()]
bb = [[bound_min[0], bound_min[1], sliceLevel],
[bound_min[0], bound_max[1], sliceLevel],
[bound_max[0], bound_max[1], sliceLevel],
[bound_max[0], bound_min[1] , sliceLevel]]
self.patterns.append(bb)
sliceLevel -= self.sliceStep.getValue()
def medial_lines(self):
patternLevels=dict()
for p in self.patterns:
patternLevels[p[0][2]] = []
for p in self.patterns:
patternLevels[p[0][2]].append(p)
output = []
for sliceLevel in sorted(patternLevels.keys(), reverse=True):
print("Slice Level: ", sliceLevel)
input = PolygonGroup(patternLevels[sliceLevel], precision=0.01, zlevel = sliceLevel)
bound_min=[self.stockMinX.getValue()-2.0*self.stockSizeX.getValue(), self.stockMinY.getValue()-2.0*self.stockSizeX.getValue()]
bound_max=[bound_min[0]+5.0*self.stockSizeX.getValue(), bound_min[1]+ 5.0*self.stockSizeY.getValue()]
#create bounding box twice the size of the stock to avoid influence of boundary on medial line on open sides
bb = [[bound_min[0], bound_min[1], 0],
[bound_min[0], bound_max[1], 0],
[bound_max[0], bound_max[1], 0],
[bound_max[0], bound_min[1] , 0]]
input.addPolygon(bb)
radius=self.tool.getValue().diameter.value/2.0+self.radialOffset.value
input = input.offset(radius=radius, rounding = self.pathRounding.getValue())
levelOutput = input.medialLines()
stock_poly = self.getStockPolygon()
#levelOutput.clip(stock_poly)
#levelOutput.clipToBoundingBox(bound_min[0], bound_min[1], bound_max[0], bound_max[1])
segments = []
for poly in levelOutput.polygons:
segment = []
for p in poly:
local_radius, cp, subpoly, ci= input.pointDistance(p)
segment.append(GPoint(position=p, dist_from_model = local_radius))
# check that start of segment has a larger radius than end (to go inside-out)
if len(segment)>0:
if segment[0].dist_from_model<segment[-1].dist_from_model:
segment.reverse()
segments.append(segment)
segments.sort(key=lambda x: x[0].dist_from_model, reverse=True)
lastpoint=segments[0][-1]
segment = []
while len(segments)>0:
#look for connected segments of greatest length and append to output
s_index=-1
rev=False
for i in range(0,len(segments)):
s = segments[i]
if dist(lastpoint.position, s[0].position) < self.precision.getValue() and \
(s_index<0 or len(s)>len(segments[s_index])):
s_index=i
rev=False
break
if dist(lastpoint.position, s[-1].position) < self.precision.getValue() and \
(s_index<0 or len(s)>len(segments[s_index])):
s_index=i
rev=True
break
if s_index<0: # if no connecting segment found, take next one from start of list
s_index=-1
if len(segment)>0:
output.append(segment)
segment = []
# find segment connected to last added segment
if len(output)>0:
for i in range(0, len(segments)):
s = segments[i]
for o in output:
if closest_point_on_open_polygon(s[0].position, [p.position for p in o])[0]<self.precision.getValue():
s_index=i
rev=False
break
if s_index<0:
s_index=0
if rev:
segments[s_index].reverse()
segment+=([p for p in segments[s_index] if stock_poly.pointInside(p.position)])
#segment+=segments[s_index]
lastpoint=segments[s_index][-1]
del segments[s_index]
# sort remaining segments by distance
#segments.sort(key=lambda s: dist(s[0].position, lastpoint.position))
if len(segment)>0:
output.append(segment)
#clean segments
print("cleaning medial lines...")
for sidx in range(0, len(output)):
s = output[sidx]
for j in range(0, sidx+1):
seg_start = output[j][0]
i=1
while i<len(s):
# go through all previous roots
if dist(s[i].position, seg_start.position)<=seg_start.dist_from_model:
del s[i]
else:
i+=1
i=0
while i<len(output):
if len(output[i])<2:
del output[i]
else:
i+=1
return output
def offsetPath(self, recursive = True):
max_iterations = self.sliceIter.getValue()
scaling=1000.0
output=[]
# sort patterns by slice levels
patternLevels=dict()
for p in self.patterns:
patternLevels[p[0][2]] = []
for p in self.patterns:
patternLevels[p[0][2]].append(p)
for sliceLevel in sorted(patternLevels.keys(), reverse=True):
print("Slice Level: ", sliceLevel)
# adding bounding box
bound_min=[self.stockMinX.getValue(), self.stockMinY.getValue()]
bound_max=[bound_min[0]+self.stockSizeX.getValue(), bound_min[1]+ self.stockSizeY.getValue()]
bb = [[bound_min[0], bound_min[1], sliceLevel],
[bound_min[0], bound_max[1], sliceLevel],
[bound_max[0], bound_max[1], sliceLevel],
[bound_max[0], bound_min[1] , sliceLevel]]
patternLevels[sliceLevel].append(bb)
trimPoly = PolygonGroup([bb], precision = self.precision.getValue(), zlevel = sliceLevel)
radius=self.tool.getValue().diameter.value/2.0+self.radialOffset.value
rounding = self.pathRounding.getValue()
iterations=max_iterations
input = PolygonGroup(patternLevels[sliceLevel], precision = self.precision.getValue(), zlevel = sliceLevel)
#input = input.offset(radius=0)
#pockets = [p for p in input.polygons if polygon_chirality(p)>0]
#input.polygons = pockets
offsetOutput = []
irounding = 0
while len(input.polygons)>0 and (max_iterations<=0 or iterations>0):
irounding+=2*self.sideStep.value
if irounding>rounding:
irounding=rounding
offset = input.offset(radius = radius, rounding = irounding)
offset.trim(trimPoly)
if self.scalloping.getValue()>0 and iterations!=max_iterations:
interLevels=[]
inter=offset
for i in range(0, int(self.scalloping.getValue())):
inter2 = inter.offset(radius=-1.5*self.sideStep.value)
inter2.trim(input)
inter2 = inter2.offset(radius=self.sideStep.value)
inter2 = inter2.offset(radius=-self.sideStep.value)
inter2.trim(input)
#if inter2.compare(input, tolerance = 0.1): # check if polygons are the "same" after trimming
# break
pathlets = inter2.getDifferentPathlets(input, tolerance = 0.1)
#pathlets = inter2
for poly in pathlets.polygons:
interLevels.append(poly)
inter = inter2
for poly in reversed(interLevels):
#close polygon
#poly.append(poly[0])
offsetOutput.append(poly)
for poly in offset.polygons:
#close polygon
poly.append(poly[0])
offsetOutput.append(poly)
print ("p", len(poly))
if recursive:
input = offset
print(len(input.polygons))
radius = self.sideStep.value
iterations -= 1
#self.patterns = input
offsetOutput.reverse()
for p in offsetOutput:
output.append(p)
return output
def offsetPathOutIn(self, recursive = True):
max_iterations = self.sliceIter.getValue()
scaling=1000.0
output=[]
#define bounding box with tool radius and offset added
bradius=self.tool.getValue().diameter.value/2.0+self.radialOffset.value
if self.toolSide.getValue() == "external":
#if max_iterations>0: # for bounding box calculations only
# bradius += max_iterations * self.sideStep.value
pass
else:
bradius = -bradius
bound_min=[self.stockMinX.getValue() - bradius, self.stockMinY.getValue()-bradius]
bound_max=[self.stockMinX.getValue()+self.stockSizeX.getValue()+bradius, self.stockMinY.getValue()+ self.stockSizeY.getValue()+bradius]
# sort patterns by slice levels
patternLevels=dict()
for p in self.patterns:
patternLevels[p[0][2]] = []
for p in self.patterns:
patternLevels[p[0][2]].append(p)
for sliceLevel in sorted(patternLevels.keys(), reverse=True):
#define bounding box
bb = [[bound_min[0], bound_min[1], sliceLevel],
[bound_min[0], bound_max[1], sliceLevel],
[bound_max[0], bound_max[1], sliceLevel],
[bound_max[0], bound_min[1] , sliceLevel]]
bbpoly = [[int(scaling*p[0]), int(scaling*p[1])] for p in bb] #Pyclipper
print("Slice Level: ", sliceLevel)
radius=self.tool.getValue().diameter.value/2.0+self.radialOffset.value
if self.toolSide.getValue() == "internal":
radius = -radius
iterations=max_iterations
if iterations<=0:
iterations=1
input = patternLevels[sliceLevel]
offsetOutput = []
while len(input)>0 and ( iterations>0):
offset=[]
clip = pyclipper.PyclipperOffset() #Pyclipper
polyclipper = pyclipper.Pyclipper() #Pyclipper
for pat in input:
outPoly=[[int(scaling*p[0]), int(scaling*p[1])] for p in pat] #Pyclipper
outPoly = pyclipper.SimplifyPolygons([outPoly])
try:
polyclipper.AddPaths(outPoly, poly_type=pyclipper.PT_SUBJECT, closed=True)
except:
None
#print "path invalid", outPoly
poly = polyclipper.Execute(pyclipper.CT_UNION, pyclipper.PFT_EVENODD, pyclipper.PFT_EVENODD)
clip.AddPaths(poly, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON)
rounding = self.pathRounding.getValue()
offset = clip.Execute( int((radius+rounding)*scaling))
offset = pyclipper.SimplifyPolygons(offset)
if rounding>0.0:
roundclipper = pyclipper.PyclipperOffset()
roundclipper.AddPaths(offset, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON)
offset = roundclipper.Execute( int(-rounding*scaling))
offset = pyclipper.CleanPolygons(offset, distance=scaling*self.precision.getValue())
# trim to outline
try:
polytrim = pyclipper.Pyclipper() #Pyclipper
polytrim.AddPath(bbpoly, poly_type=pyclipper.PT_CLIP, closed=True)
polytrim.AddPaths(offset, poly_type=pyclipper.PT_SUBJECT, closed=True)
offset = polytrim.Execute(pyclipper.CT_INTERSECTION, pyclipper.PFT_EVENODD, pyclipper.PFT_EVENODD)
except:
print("clipping intersection error")
#print (len(offset))
input = []
for poly in offset:
offsetOutput.append([[x[0]/scaling, x[1]/scaling, sliceLevel] for x in reversed(poly)])
if recursive:
input.append([[x[0]/scaling, x[1]/scaling, sliceLevel] for x in poly])
if self.toolSide.getValue() == "external":
radius = self.sideStep.value
else:
radius = -self.sideStep.value
iterations -= 1
#self.patterns = input
#offsetOutput.reverse()
lastpoint = None
for p in offsetOutput:
closest_point_index = 0
path_closed=True
remainder_path=[] # append the start of a boundary path to the first boundary point to the end
on_boundary=False
opt_path=[]
for i in range(0, len(p)):
#check if point lies on boundary
bdist, bpoint, bindex = closest_point_on_polygon(p[i], bb)
if bdist<0.001 and False: # (TURNED OFF, buggy) point lies on boundary; skip this point
# if this is the first boundary point of the path, append the start to the end
if path_closed:
remainder_path = opt_path
remainder_path.append(p[i])
opt_path=[]
path_closed=False
else:
if not on_boundary: # if it is the first point on boundary, add it
#flush path up to here to output
opt_path.append(p[i])
if len(opt_path)>0:
output.append(opt_path)
lastpoint = opt_path[-1]
opt_path=[]
on_boundary=True
else:
if on_boundary and i>0:
opt_path.append(p[i-1])
on_boundary=False
opt_path.append(p[i])
opt_path+=remainder_path
if lastpoint is not None and path_closed:
for i in range(0, len(p)):
# find closest point from last position
if dist(lastpoint, p[i]) < dist(lastpoint, opt_path[closest_point_index]):
closest_point_index = i
opt_path = opt_path[closest_point_index:] + opt_path [:closest_point_index]
# last point same as first point on closed paths (explicitly add it here)
opt_path.append(opt_path[0])
if len(opt_path)>0:
lastpoint = opt_path[-1]
output.append(opt_path)
return output
def calcPath(self):
patterns = self.patterns
if self.operation.value=="Medial Lines":
medial = self.medial_lines()
medialGcode = GCode()
lastpoint = None
for path in medial:
if lastpoint is None:
lastpoint = path[0]
medialGcode.append(GPoint(position=(lastpoint.position[0], lastpoint.position[1], self.traverseHeight.getValue()), rapid=True))
if dist(path[0].position, lastpoint.position)>self.precision.getValue(): # if points are not the same, perform a lift
medialGcode.append(GPoint(position=(lastpoint.position[0], lastpoint.position[1], self.traverseHeight.getValue()), rapid=True))
medialGcode.append(GPoint(position=(path[0].position[0], path[0].position[1], self.traverseHeight.getValue()), rapid=True))
for p in path:
medialGcode.append(p)
lastpoint = p
if lastpoint is not None:
medialGcode.append(GPoint(position=(lastpoint.position[0], lastpoint.position[1], self.traverseHeight.getValue()),rapid=True))
return medialGcode
if self.operation.value=="Outline" or self.operation.value=="Slice" or self.operation.value=="Slice & Drop":
recursive = True
offset_path=[]
lastpoint = None
if self.direction.getValue() == "inside out":
offset_path=self.offsetPath(recursive)
self.path=GCode()
patterns = []
#self.path+=p
optimisePath=True
if optimisePath:
path_tree = polygon_tree()
for p in reversed( offset_path):
path_tree.insert(p)
#path_tree.optimise()
#offset_path = path_tree.toList()
#if self.direction.getValue() == "inside out": # reverse path order (paths are naturally inside outwards
offset_path = path_tree.toGPoints()
else:
offset_path = [[GPoint(position=(p[0], p[1], p[2])) for p in segment] for segment in offset_path]
else: # outside-in roughing
offset_path=self.offsetPathOutIn(recursive)
self.path=GCode()
#offset_path = [[GPoint(position=(p[0], p[1], p[2])) for p in segment] for segment in offset_path]
optimisePath = True
if optimisePath:
path_tree = polygon_tree()
for p in reversed(offset_path):
path_tree.insert(p)
#self.viewUpdater()
#path_tree.optimise()
# offset_path = path_tree.toList()
# if self.direction.getValue() == "inside out": # reverse path order (paths are naturally inside outwards
offset_path = [seg for seg in reversed(path_tree.toGPoints())]
else:
offset_path = [[GPoint(position=(p[0], p[1], p[2])) for p in segment] for segment in offset_path]
#else:
# offset_path = path_tree.toGPointsOutIn()
slice_patterns=[]
#for path in offset_path:
while len(offset_path)>0:
#do_rapid = True
#try to optimise paths by finding closest point in new contour path to last point
#if lastpoint is not None:
#pick first polygon that contains lastpoint:
#selected_path_index = 0
#path = offset_path[selected_path_index]
#opt_path = offset_path[selected_path_index]
#del offset_path[selected_path_index]
#closest_point_index = 0
#for i in range(0, len(path)):
# if dist(lastpoint, path[i]) < dist(lastpoint, path[closest_point_index]):
# closest_point_index = i
#opt_path = path[closest_point_index:] + path [:closest_point_index]
#else:
path = offset_path[0]
del offset_path[0]
opt_path = path
if not self.operation.value=="Slice & Drop":
if lastpoint is None or dist(lastpoint.position, opt_path[0].position)>2*self.sideStep.value:
if lastpoint is not None:
self.path.append(GPoint(position=(lastpoint.position[0], lastpoint.position[1], self.traverseHeight.value), rapid=True))
self.path.append(GPoint(position=(opt_path[0].position[0], opt_path[0].position[1], self.traverseHeight.value), rapid=True))
for p in opt_path:
self.path.append(p)
#self.path.append(GPoint(position=(opt_path[0].position[0], opt_path[0].position[1], opt_path[0].position[2])))
lastpoint = opt_path[-1]
else:
slice_patterns.append([p.position for p in opt_path])
if self.operation.value == "Slice & Drop":
self.patterns=slice_patterns
self.path=self.dropPathToModel()
else:
self.path.append(GPoint(position=(lastpoint.position[0], lastpoint.position[1], self.traverseHeight.value), rapid=True))
return self.path
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,330 | codemakeshare/g-mint | refs/heads/master | /solids.py | from geometry import *
from numpy import *
import math
from gcode import *
import time
#import pyclipper
import multiprocessing as mp
#import subprocess
from random import randint
def RandomPoly(maxWidth, maxHeight, vertCnt):
result = []
for _ in range(vertCnt):
result.append(Point(randint(0, maxWidth), randint(0, maxHeight)))
return result
class facet:
def __init__(self, normal):
self.normal=normal;
self.vertices=[]
def __eq__(self, of):
return self.vertices == of.vertices
def __ne__(self, of):
return not self.__eq__(of)
def load_stl_file(filename):
infile = []
infile = open(filename)
datalines = infile.readlines();
last_facet = []
facets = []
for l in datalines:
l_el = l.split();
if l_el[0] == "facet" and l_el[1] == "normal":
last_facet = facet([float(x) for x in l_el[2:]])
elif l_el[0] == "vertex":
last_facet.vertices.append(array([float(x) / 1.0 for x in l_el[1:]]))
elif l_el[0] == "endfacet":
facets.append(last_facet)
#faces(pos=last_facet.vertices, normal=last_facet.normal)
last_facet = []
return facets
class Solid:
def __init__(self):
self.map=[]
self.update_visual=False
self.refmap=None
self.material=None
self.facets=None
self.minv=[0, 0, 0]
self.maxv=[0, 0, 0]
self.filename=None
def load(self, filename):
self.facets=load_stl_file(filename)
self.filename=filename
self.get_bounding_box()
def scale(self, scale_factors):
for f in self.facets:
for p in f.vertices:
p[0]=p[0]*scale_factors[0]
p[1]=p[1]*scale_factors[1]
p[2]=p[2]*scale_factors[2]
self.get_bounding_box()
#force recomputation of refmap as mesh has changed
self.refmap=None
def rotate_x(self):
for f in self.facets:
for p in f.vertices:
tmp=p[2]
p[0]=p[0]
p[2]=-p[1]
p[1]=tmp
self.get_bounding_box()
#force recomputation of refmap as mesh has changed
self.refmap=None
def rotate_y(self):
for f in self.facets:
for p in f.vertices:
tmp=p[2]
p[2]=-p[0]
p[1]=p[1]
p[0]=tmp
self.get_bounding_box()
#force recomputation of refmap as mesh has changed
self.refmap=None
def rotate_z(self):
for f in self.facets:
for p in f.vertices:
tmp=p[1]
p[1]=-p[0]
p[0]=tmp
p[2]=p[2]
self.get_bounding_box()
#force recomputation of refmap as mesh has changed
self.refmap=None
def get_bounding_box(self):
if self.facets==None:
return
self.minv=self.facets[0].vertices[0]
self.maxv=self.facets[0].vertices[0]
self.leftmost_point_facet=self.facets[0]
self.leftmost_point=self.facets[0].vertices[0]
for f in self.facets:
for p in f.vertices:
self.minv=pmin(self.minv,p)
self.maxv=pmax(self.maxv,p)
if p[0]<self.leftmost_point[0]:
self.leftmost_point_facet=f
self.leftmost_point=p
self.waterlevel=self.minv[2]
print(self.minv, self.maxv, "waterlevel", self.waterlevel)
def add_padding(self, pad3D):
self.minv[0]-=pad3D[0]
self.minv[1]-=pad3D[1]
self.minv[2]-=pad3D[2]
self.maxv[0]+=pad3D[0]
self.maxv[1]+=pad3D[1]
self.maxv[2]+=pad3D[2]
def run_collapse(facet):
return run_collapse.function(facet, run_collapse.inverted)
def run_collapse_init(function, task_options, inverted):
run_collapse.function=function
#run_collapse.task=task_options
run_collapse.inverted=inverted
def run_pool(index):
return run_pool.function(index, *run_pool.parameters)
def run_pool_init(function, *parameters):
run_pool.function=function
run_pool.parameters=parameters
class CAM_Solid(Solid):
def calc_ref_map(self, refgrid, radius=0):
if self.refmap!=None and self.refgrid==refgrid and self.refmap_radius>=radius and self.refmap_radius<=3 * radius:
print("using cached refmap with grid %i and radius %i"%(self.refgrid, self.refmap_radius))
return
self.refgrid=refgrid
self.refmap_radius=radius
print("Computing reference map with grid %i and radius %i..."%(self.refgrid, self.refmap_radius))
minv=self.minv
refmap=[[[] for y in frange(self.minv[1],self.maxv[1]+4*refgrid, refgrid)]for x in frange(self.minv[0],self.maxv[0]+4*refgrid, refgrid)]
refmap_indexed=[[[] for y in frange(self.minv[1],self.maxv[1]+4*refgrid, refgrid)]for x in frange(self.minv[0],self.maxv[0]+4*refgrid, refgrid)]
# draw all triangles
#for f in self.facets:
for i in range(0, len(self.facets)):
f=self.facets[i]
tmin=f.vertices[0]
tmax=f.vertices[0]
for v in f.vertices:
tmin=pmin(tmin, v)
tmax=pmax(tmax, v)
f.maxHeight=tmax[2]
for ix in range(max(0,int((tmin[0]-minv[0]-radius)/refgrid)),min(len(refmap),int((tmax[0]-minv[0]+radius)/refgrid+1))):
for iy in range(max(0,int((tmin[1]-minv[1]-radius)/refgrid)),min(len(refmap[0]),int((tmax[1]-minv[1]+radius)/refgrid+1))):
refmap[ix][iy].append(f)
refmap_indexed[ix][iy].append(i)
# sort triangles by highest point (descending order)
sorted(refmap[ix][iy], key=lambda f: f.maxHeight, reverse=True)
self.refmap=refmap
self.refmap_indexed=refmap_indexed
# determines state of facet (belongs to surface=1, does not belong=-1, undecided (vertical face) =0
def projectFacetToSurface(self, f, inverted):
is_surface=-1
cp=crossproduct(f.vertices[1]-f.vertices[0], f.vertices[2]-f.vertices[0])
vertical= norm(cp)>0.01 and is_num_equal(cp[2], 0.0, 0.01)
if vertical:
# keep vertical surfaces for now, but tag them as not surface (will be determined later)
is_surface= -1
return is_surface
#for v in f.vertices:
t=f.vertices
m=[(t[0][0]+t[1][0]+t[2][0])/3.0, (t[0][1]+t[1][1]+t[2][1])/3.0, (t[0][2]+t[1][2]+t[2][2])/3.0]
dm=self.get_height_surface(m[0], m[1], inverted)
#dc, onEdge=map(self.get_height_surface_edgetest, [p[0] for p in t], [p[1] for p in t], [inverted for p in t])
#dc.append(dm)
if ( inverted and (dm==None or m[2]<=dm+0.000001)) or \
(not inverted and (dm==None or m[2]>=dm-0.000001) ):
is_surface=1
#for i in range(0, len(t)):
# if ( not inverted and ( t[i][2]>=dc[i]-0.001)) or \
# ( inverted and ( t[i][2]<=dc[i]+0.001) ):
# is_surface=1
return is_surface
def projectFacetToSurfaceLazy(self, f, inverted):
is_surface=-1
t=f.vertices
m=[(t[0][0]+t[1][0]+t[2][0])/3.0, (t[0][1]+t[1][1]+t[2][1])/3.0, (t[0][2]+t[1][2]+t[2][2])/3.0]
dm=self.get_height_surface(m[0], m[1], inverted)
mapresults=map(self.get_height_surface_edgetest, [p[0] for p in t], [p[1] for p in t], [inverted for p in t])
dc=[x[0] for x in mapresults]
onEdge=[x[1] for x in mapresults]
cp=crossproduct(f.vertices[1]-f.vertices[0], f.vertices[2]-f.vertices[0])
vertical= norm(cp)>0.0000001 and is_num_equal(cp[2], 0.0, 0.001)
if vertical:
# keep vertical surfaces for now, but tag them as not surface (will be determined later)
is_surface= -1
return is_surface
count_equal=0
edgeTest=True
for i in range(0, len(t)):
if dc[i]==None or ((not inverted and t[i][2]>=dc[i]-0.00000001) or \
( inverted and t[i][2]<=dc[i]+0.00000001 )):
count_equal+=1
if onEdge[i]==False:
edgeTest=False
m_is_surface=-1
if ( inverted and (dm==None or m[2]<=dm+0.00000001)) or \
(not inverted and (dm==None or m[2]>=dm-0.00000001) ):
m_is_surface=1
if count_equal>=3 or (count_equal>0 and edgeTest):
is_surface=1
else:
is_surface=-1
return is_surface
def collapse_to_surface(self, inverted=False):
self.calc_ref_map(1, 1)
#g=float(self.refgrid)
new_facets=[]
#lcount=0
if inverted:
self.waterlevel=self.maxv[2]
else:
self.waterlevel=self.minv[2]
print(self.waterlevel)
pool=mp.Pool(None, run_collapse_init, [self.projectFacetToSurface, self, inverted] )
results=pool.map(run_collapse, self.facets)
#run_collapse_init(self.projectFacetToSurfaceLazy, self, inverted)
#results=map(run_collapse, self.facets)
# for f in self.facets:
# facets_added=1
# while facets_added>0:
# facets_added=0
# for i in range(0, len(results)):
# # iteratively tag vertical surfaces that are connected to non-vertical surfaces
# if results[i]==0:
# t=self.facets[i].vertices
# triangles=self.get_local_facet_indices(t[0][0], t[0][1])+self.get_local_facet_indices(t[1][0], t[1][1])+self.get_local_facet_indices(t[2][0], t[2][1])
#
# for j in triangles:
# #if any non-vertical triangle is connected, accept the facet
# u=self.facets[j].vertices
# if i!=j and results[j]==1 and shares_points(t, u)==2:
## is_higher=True
## for tv in t:
## for uv in u:
## if tv[2]<uv[2]:
## is_higher=False
## if is_higher:
# results[i]=1
# facets_added+=1
for i in range(0, len(results)):
if results[i]==1:
new_facets.append(self.facets[i])
self.facets=new_facets
self.get_bounding_box()
#force recomputation of refmap as mesh has changed
self.refmap=None
def calc_height_map_pixel(self, index, inverted):
y=index/len(self.xrange)
x=index%len(self.xrange)
depth=None
for f in self.get_local_facets(self.xrange[x],self.yrange[y]):
#for f in self.facets:
inTriangle, projectedPoint, onEdge=getPlaneHeight([self.xrange[x],self.yrange[y], 0.0], f.vertices)
if inTriangle:
if depth==None or (not inverted and projectedPoint[2]>depth) or (inverted and projectedPoint[2]<depth):
#print inTriangle, projectedPoint
depth=projectedPoint[2]
#depth=1.0
#if depth !=None:
# self.map[x][y]=depth
# self.update_visual=True
return depth
#if y % (len(self.map[0])/10)==0:
# print (".")
def calc_height_map_scanning(self, grid=1.0, padding=0.0, inverted=False, waterlevel='min'):
self.gridsize=grid
minv=self.minv
maxv=self.maxv
padding=10
self.xrange=frange(minv[0]-padding,maxv[0]+padding+grid, grid)
self.yrange=frange(minv[1]-padding,maxv[1]+padding+grid, grid)
default_value=float(minv[2])
if waterlevel=='max':
default_value=maxv[2]
if waterlevel=='min':
default_value=minv[2]
if waterlevel=='middle':
default_value=(minv[2]+maxv[2])/2.0
print("calculating reference map")
self.calc_ref_map(1, 1)
print("calculating height map")
# for y in range(0,len(self.map[0])):
# for x in range(0,len(self.map)):
# r=self.calc_height_map_pixel( x+len(self.xrange)* y, inverted)
# if r!=None:
# self.map[x][y]=r
pool=mp.Pool(None, run_pool_init, [self.calc_height_map_pixel, inverted] )
mresults=pool.map_async(run_pool, [x+len(self.xrange)* y for y in range(0, len(self.yrange)) for x in range(0, len(self.xrange))])
remaining=0
while not (mresults.ready()):
if mresults._number_left!=remaining:
remaining = mresults._number_left
print("Waiting for", remaining, "tasks to complete...")
time.sleep(1)
pool.close()
pool.join()
results=mresults.get()
self.map= [mp.Array('f',[default_value for y in self.yrange])for x in self.xrange]
self.map_waterlevel=default_value
for y in range(0,len(self.yrange)):
for x in range(0,len(self.xrange)):
r=results[x+len(self.xrange)* y]
if r!=None:
self.map[x][y]=r
self.material=None
def getDepthFromMap(self, x, y):
g=float(self.gridsize)
gx=float(x-self.xrange[0])/g
gy=float(y-self.yrange[0])/g
return self.getDepthFromMapGrid(gx, gy)
def getDepthFromMapGrid(self, gx, gy):
if (int(gx)<0 or int(gx)>len(self.map)-1 or int(gy)<0 or int(gy)>len(self.map[0])-1):
return self.map_waterlevel
return self.map[int(gx)][int(gy)]
def interpolate_gaps(self, unmodified_value):
max_height=self.minv[2]
deepest_point=self.maxv[2]
self.bmap=self.map
for y in range(0,len(self.bmap[0])):
last_height_index=-1
next_height_index=-1
for x in range(0,len(self.bmap)):
if self.bmap[x][y]!= unmodified_value:
last_height_index=x
next_height_index=-1
max_height = max(max_height, self.bmap[x][y])
deepest_point= min(deepest_point, self.bmap[x][y])
else:
if next_height_index==-1:
# search next voxel that is part of the object
next_height_index=x+1
while (next_height_index<len(self.map)) and (self.bmap[next_height_index][y]==unmodified_value):
next_height_index+=1
if next_height_index!=len(self.bmap):
if last_height_index==-1:
int_height =self.map[next_height_index][y]
else:
int_index=((x-last_height_index)/float(next_height_index-last_height_index))
#int_index=1
int_height=(1.0-int_index)* self.map[last_height_index][y]+(int_index)*self.map[next_height_index][y]
else:
if last_height_index==-1:
int_height=unmodified_value
else:
int_height=self.bmap[last_height_index][y]
self.bmap[x][y]=int_height
print(max_height, deepest_point, "max thickness:", max_height-deepest_point)
self.maxv[2]=max_height
for y in range(0,len(self.bmap[0])):
for x in range(0,len(self.bmap)):
if self.bmap[x][y]==unmodified_value:
self.bmap[x][y]=max_height
self.update_visual=True
#force recomputation of refmap as mesh has changed
self.refmap=None
def smooth_height_map(self):
map=self.map
for x in range(1,len(map)-1):
for y in range(1,len(map[0])-1):
map[x][y]=(map[x][y]+(map[x-1][y-1]+map[x][y-1]+map[x+1][y-1]+map[x-1][y]+map[x+1][y]+map[x-1][y+1]+map[x][y+1]+map[x+1][y+1])/8.0)/2.0
self.update_visual=True
def get_local_facets(self, x, y):
g=float(self.refgrid)
gx=max(0, min(int(float(x-self.minv[0])/g), len(self.refmap)-1))
gy=max(0, min(int(float(y-self.minv[1])/g), len(self.refmap[0])-1))
# assemble all relevant triangles:
return self.refmap[gx][gy]
def get_local_facet_indices(self, x, y):
g=float(self.refgrid)
gx=int(float(x-self.minv[0])/g)
gy=int(float(y-self.minv[1])/g)
# assemble all relevant triangles:
return self.refmap_indexed[gx][gy]
def get_height_surface(self, x, y, inverted=True):
tp=vec((x,y,0))
waterlevel=self.minv[2]
depth=None
pointInModel=False
# assemble all relevant triangles:
triangles=self.get_local_facets(x, y)
for f in triangles:
inTriangle, tp, onEdge=getPlaneHeight([x, y, 0.0], f.vertices)
if inTriangle:
if depth==None or (not inverted and tp[2]>depth) or (inverted and tp[2]<depth):
depth=tp[2]
return depth
def get_height_surface_edgetest(self, x, y, inverted=True):
tp=vec((x,y,0))
waterlevel=self.minv[2]
depth=None
pointInModel=False
# assemble all relevant triangles:
triangles=self.get_local_facets(x, y)
edgeTest=False
for f in triangles:
inTriangle, tp, onEdge=getPlaneHeight([x, y, 0.0], f.vertices)
if inTriangle:
if depth==None or (not inverted and tp[2]>depth) or (inverted and tp[2]<depth):
depth=tp[2]
if onEdge:
edgeTest=True
return [depth, edgeTest]
def get_height_ball_geometric(self, x, y, radius):
tp=vec((x,y,0))
g=float(self.refgrid)
gx=int(float(x-self.minv[0])/g)
gy=int(float(y-self.minv[1])/g)
depth=None
# assemble all relevant triangles:
triangles=self.refmap[gx][gy]
for f in triangles:
#check edges/vertices:
if depth is None or f.maxHeight>depth:
#check point inside triangle
n=normalize(crossproduct(f.vertices[1]-f.vertices[0], f.vertices[2]-f.vertices[0] ))#+\
#crossproduct(vec(f.vertices[0])-vec(f.vertices[1]), vec(f.vertices[2])-vec(f.vertices[1]) )+\
#crossproduct(vec(f.vertices[0])-vec(f.vertices[2]), vec(f.vertices[1])-vec(f.vertices[2]) ))
if n[2]<0:
n=- n
#inTriangle, projectedPoint, onEdge=getPlaneHeight([x, y, 0.0], f.vertices)
#if inTriangle:
# pointInModel=True
inTriangle, projectedPoint, onEdge=getPlaneHeight([x-radius*n[0], y-radius*n[1], 0.0], f.vertices)
if inTriangle:
tp=[projectedPoint[0]+radius*n[0], projectedPoint[1]+radius*n[1],projectedPoint[2]+radius*n[2] -radius]
if depth==None or tp[2]>depth:
depth=tp[2]
#check edges/vertices:
for i in range(0, 3):
v1=f.vertices[i]
v2=f.vertices[(i+1)%3]
onPoint, pp=dropSphereLine(v1, v2, [x, y, 0], radius)
if onPoint and (depth==None or pp>depth):
depth=pp
onPoint, pp=dropSpherePoint(v1, x, y, radius)
if onPoint and (depth==None or pp>depth):
depth=pp
in_contact=True
inside_model=self.get_height_surface(x, y)!=None
if depth==None or (not inside_model and depth<self.waterlevel):
depth=self.waterlevel
in_contact=False
return depth, inside_model, in_contact
def get_height_slotdrill_geometric(self, x, y, radius):
tp=vec((x,y,0))
g=float(self.refgrid)
gx=int(float(x-self.minv[0])/g)
gy=int(float(y-self.minv[1])/g)
depth=None
# assemble all relevant triangles:
triangles=self.refmap[gx][gy]
for f in triangles:
#check edges/vertices:
if depth is None or f.maxHeight>depth:
#check point inside triangle
# triangle normal vector
n=normalize(crossproduct(f.vertices[1]-f.vertices[0], f.vertices[2]-f.vertices[0] ))
if n[2]<0:
n=- n
#adjust test point radius so that virtual sphere touches where cylinder end touches
# (this results in a larger sphere than the cutter, unless the triangle is vertical)
# special case: horizontal triangles (infite sphere, but trivial)
denom = sqrt(1.0-n[2]**2)
# check if triangle is not horizontal (denom is zero):
if denom>0.00000001:
rv = radius/denom
cpx = x-rv*n[0]
cpy = y-rv*n[1]
inTriangle, projectedPoint, onEdge=getPlaneHeight([cpx, cpy, 0.0], f.vertices)
if inTriangle:
tp=[projectedPoint[0]+rv*n[0], projectedPoint[1]+rv*n[1],projectedPoint[2]]
if depth==None or tp[2]>depth:
depth=tp[2]
None
else: # triangle horizontal - take depth from one of the points:
tp = f.vertices[0]
center = [x, y, tp[2]]
# check if cutter is within triangle (center in triangle. corner points are tested later)
if PointInTriangle(center, f.vertices):
if depth==None or tp[2]>depth:
depth=tp[2]
#check edges/vertices:
for i in range(0, 3):
v1=f.vertices[i]
v2=f.vertices[(i+1)%3]
#find intersections between cutter circle and lines
ip = intersectLineCircle2D(v1, v2, [x, y], radius)
#project resulting intersection points onto 3D edges
clipped_ip = []
for p in ip:
onLine, height = dropSphereLine(v1, v2, [p[0], p[1], 0], 0.000001)
if onLine:
clipped_ip.append([p[0], p[1], height-0.00001])
for p in clipped_ip:
if (depth==None or p[2]>depth):
depth=p[2]
None
if dist ([v1[0], v1[1]], [x, y])<=radius and (depth==None or v1[2]>depth):
depth=v1[2]
None
in_contact=True
inside_model=self.get_height_surface(x, y)!=None
if depth==None or (not inside_model and depth<self.waterlevel):
depth=self.waterlevel
in_contact=False
return depth, inside_model, in_contact
def get_height_slotdrill_map(self, x, y, radius):
g=float(self.gridsize)
gx=float(x-self.xrange[0])/g
gy=float(y-self.yrange[0])/g
depth=self.getDepthFromMapGrid(gx, gy)
for x in range(int(gx-radius/g), int(gx+radius/g+1.0)):
for y in range(int(gy-radius/g), int(gy+radius/g+1.0)):
dx=(float(x)-gx)*g
dy=(float(y)-gy)*g
rs=radius*radius
if (dx*dx+dy*dy)<rs:
depth=max(depth, self.getDepthFromMapGrid(x, y))
return depth, True, True
def get_height_ball_map(self, x, y, radius):
g=float(self.gridsize)
gx=float(x-self.xrange[0])/g
gy=float(y-self.yrange[0])/g
depth=self.getDepthFromMapGrid(gx, gy)
dx=0.0
dy=0.0
rs=0.0
r2ds=0.0
for x in range(int(gx-radius/g),int(gx+radius/g+1.0)):
for y in range(int(gy-radius/g),int(gy+radius/g+1.0)):
dx=(float(x)-gx)*g
dy=(float(y)-gy)*g
rs=radius*radius
r2ds=dx*dx+dy*dy
if r2ds<rs:
h=math.sqrt(rs-r2ds)
depth=max(depth, self.getDepthFromMapGrid(x, y)+h-radius)
return depth, True, True
def append_point(self, path, x, y, radius, deviation, limit_depth, min_stepx=0.1, height_function=[], max_step=5.0, depth_hint=None):
#depth=self.get_height_slotdrill(x,y,radius)
#depth=max(self.get_height_ball(x,y,radius), limit_depth)
in_contact=True
height, inside_model, in_contact=0, 0, 0
if depth_hint!=None:
[height, inside_model, in_contact]=depth_hint
else:
height, inside_model, in_contact=height_function(x,y,radius)
depth=max(height, limit_depth)
if len(path)==0:
path.append(GPoint(position=[x, y, depth], inside_model=inside_model, in_contact=in_contact))
return
prev_point=path[-1].position
height2, inside_model2, in_contact2=height_function((prev_point[0]+x)/2.0, (prev_point[1]+y)/2.0,radius)
depth2=max(height2, limit_depth)
intpol_depth=(prev_point[2]+depth)/2.0
if (abs(prev_point[0]-x)>max_step or abs(prev_point[1]-y)>max_step) or\
((abs(depth2-intpol_depth)>deviation)\
and (abs(prev_point[0]-x)>min_stepx \
or abs(prev_point[1]-y)>min_stepx)):
# if (abs(prev_point[0]-x)>max_step or abs(prev_point[1]-y)>max_step) or (abs(depth-prev_point[2])>deviation) and (abs(prev_point[0]-x)>min_stepx or abs(prev_point[1]-y)>min_stepx):
#recursively reduce step size by halving last step
self.append_point(path, (prev_point[0]+x)/2.0, (prev_point[1]+y)/2.0, radius, deviation, limit_depth, min_stepx, height_function, max_step, [height2, inside_model2, in_contact2])
self.append_point(path, x, y, radius, deviation, limit_depth, min_stepx, height_function, max_step)
prev_point=path[-1].position
else:
# if depth-prev_point[2]>deviation:
# path.append(GPoint(position=(prev_point[0], prev_point[1],depth), inside_model=inside_model, in_contact=in_contact))
# #box(pos=(prev_point[0], prev_point[1],depth), color=(0,1,0))
#
# if depth-prev_point[2]<-deviation:
# path.append(GPoint(position=(x,y,prev_point[2]), inside_model=inside_model, in_contact=in_contact))
# #box(pos=(x,y,prev_point[2]), color=(1,0,0))
#
# #apply cut to simulated material
# if self.material != None:
# self.material.apply_slotdrill((x,y,depth), radius)
path.append(GPoint(position=[x, y, depth], inside_model=inside_model, in_contact=in_contact))
#box(pos=(x,y,depth))
#box(pos=(x,y,depth))
def follow_surface(self, trace_path, traverse_height, max_depth, tool_diameter, height_function, deviation=0.5, min_stepx=0.2, margin=0):
path=[]
#start_pos=trace_path[0]
print("traverse:", traverse_height)
print("waterlevel", self.waterlevel)
#path.append((start_pos[0], start_pos[1], traverse_height))
for p in trace_path:
self.append_point(path=path, x=p[0], y=p[1],radius= tool_diameter/2.0 + margin, deviation=deviation, limit_depth=max_depth, min_stepx=min_stepx, height_function=height_function)
for p in path:
p.position[2]+=margin
#path.append((path[-1][0], path[-1][1], traverse_height))
#curve(pos=path, color=(0.5, 0.5, 1.0))
return path
def calc_outline(self):
self.calc_ref_map(3.0, 1.0)
#get leftmost point
outline=[]
#lpf=self.leftmost_point_facet
sp=self.leftmost_point
#waterlevel=sp[2]
candsp=sp
lastp=sp-[1, 0, 0]
outline.append(tuple(sp))
finished=False
print("computing outline")
while not finished:
minAngle=None
triangles=self.get_local_facets(sp[0], sp[1])
np=None
for f in triangles:
sharesPoint=False
for v in f.vertices:
if tuple(v)==tuple(sp):
sharesPoint=True
if sharesPoint:
for v in f.vertices:
if not tuple(v)in outline[1:]:
if not (sp[0]==lastp[0] and sp[1]==lastp[1]) and not (v[0]==sp[0] and v[1]==sp[1]):
prevEdge=lastp-sp
alpha=full_angle2d([prevEdge[0], prevEdge[1]], [v[0]-sp[0], v[1]-sp[1]] )
if minAngle==None or (alpha>minAngle):
np=v
minAngle=alpha
candsp=np
if candsp!=None:
lastp =sp
sp=candsp
#print sp
outline.append(tuple(sp))
else: finished=True
if tuple(sp)==tuple(self.leftmost_point):# or tuple(sp) in outline:
finished=True
self.outline=outline
def calcSlice(self, sliceLevel):
segments=[]
for f in self.facets:
#check if there are points above and below slice level
points = []
points.append(horizontalLineSlice(f.vertices[0], f.vertices[1], sliceLevel, tolerance_offset=0.00001))
points.append(horizontalLineSlice(f.vertices[1], f.vertices[2], sliceLevel, tolerance_offset=0.00001))
points.append(horizontalLineSlice(f.vertices[2], f.vertices[0], sliceLevel, tolerance_offset=0.00001))
segment=[]
for p in points:
if p is not None:
segment.append(p)
if len(segment)>1:
segments.append(segment)
sorted_segments = []
if len(segments)>1:
sorted_segment = segments[0]
del segments[0]
while len(segments)>0:
lastpoint = sorted_segment[-1]
segmentFound = False
for i in range(0, len(segments)):
s=segments[i]
if dist(s[0], lastpoint)<0.001:
segmentFound = True
sorted_segment.append(s[1])
del segments[i]
break
if dist(s[1], lastpoint)<0.001:
segmentFound = True
sorted_segment.append(s[0])
del segments[i]
break
if not segmentFound:
#close contour
#sorted_segment.append(sorted_segment[0])
sorted_segments.append(sorted_segment)
sorted_segment = segments[0]
del segments[0]
sorted_segments.append(sorted_segment)
return sorted_segments
| {"/tools/lathetask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/tools/pathtool.py": ["/gcode.py", "/geometry.py"], "/tools/textengrave.py": ["/gcode.py", "/tools/milltask.py"], "/gcode_editor.py": ["/gcode.py"], "/gcode.py": ["/geometry.py"], "/tools/svgengrave.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py", "/tools/milltask.py"], "/tools/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/taskdialog.py": ["/tools/modeltool.py", "/tools/milltask.py", "/tools/pathtool.py", "/tools/threading_tool.py", "/tools/timing_pulley.py", "/tools/lathetask.py", "/tools/lathethreadingtool.py", "/tools/svgengrave.py", "/tools/textengrave.py"], "/mint.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tengrave.py": ["/solids.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py", "/tools/textengrave.py", "/tools/tool.py", "/tools/modeltool.py"], "/tools/tool_lathe_insert.py": ["/polygons.py"], "/objectviewer2D.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/lint.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py", "/objectviewer.py", "/gcode_editor.py"], "/tools/timing_pulley.py": ["/gcode.py"], "/grbldialog.py": ["/objectviewer.py", "/tools/pathtool.py"], "/cameraviewer.py": ["/OrthoGLViewWidget.py"], "/tools/lathethreadingtool.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/modeldialog.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/pathtool.py", "/tools/milltask.py", "/solids.py", "/objectviewer.py"], "/pathdialog.py": ["/tools/pathtool.py", "/objectviewer.py"], "/objectviewer.py": ["/OrthoGLViewWidget.py", "/solids.py"], "/tools/threading_tool.py": ["/gcode.py"], "/gui.py": ["/tools/modeltool.py", "/tools/tool.py", "/tools/milltask.py", "/solids.py", "/modeldialog.py", "/pathdialog.py", "/taskdialog.py", "/grbldialog.py"], "/polygons.py": ["/gcode.py"], "/tools/milltask.py": ["/geometry.py", "/solids.py", "/polygons.py", "/gcode.py"], "/solids.py": ["/geometry.py", "/gcode.py"]} |
57,331 | pombredanne/new-github-issue-url-py | refs/heads/master | /test.py | from new_github_issue_url import IssueUrl
options = {
"user": 'aligoren',
"repo": 'new-github-issue-url-py',
"title": "I'm just a human",
"body": '\n\n\n---\nI\'m a human. Please be nice.',
}
issue_url = IssueUrl(options)
issue_url.opn()
# print(issue_url.url) | {"/test.py": ["/new_github_issue_url.py"]} |
57,332 | pombredanne/new-github-issue-url-py | refs/heads/master | /new_github_issue_url.py | from json import dumps
try:
from urllib import urlencode, unquote
from urlparse import urlparse, parse_qsl, ParseResult
except ImportError:
# Python 3 fallback
from urllib.parse import (
urlencode, unquote, urlparse, parse_qsl, ParseResult
)
import webbrowser
class IssueUrl:
def __init__(self, options):
repoUrl = None
self.opts = options
if "repoUrl" in self.opts:
repoUrl = self.opts["repoUrl"]
try:
del self.opts["user"]
del self.opts["repo"]
except:
pass
elif "user" in self.opts and "repo" in options:
try:
del self.opts["repoUrl"]
except:
pass
repoUrl = "https://github.com/{0}/{1}".format(self.opts["user"], self.opts["repo"])
else:
raise KeyError('You need to specify either the `repoUrl` option or both the `user` and `repo` options')
self.url = "{0}/issues/new".format(repoUrl)
self.types = [
'body', 'title', 'labels', 'template', 'milestone', 'assignee', 'projects'
]
def add_url_params(self, url, params):
""" Add GET params to provided URL being aware of existing.
:param url: string of target URL
:param params: dict containing requested params to be added
:return: string with updated URL
>> url = 'http://stackoverflow.com/test?answers=true'
>> new_params = {'answers': False, 'data': ['some','values']}
>> add_url_params(url, new_params)
'http://stackoverflow.com/test?data=some&data=values&answers=false'
Source: https://stackoverflow.com/a/25580545/3821823
"""
# Unquoting URL first so we don't loose existing args
url = unquote(url)
# Extracting url info
parsed_url = urlparse(url)
# Extracting URL arguments from parsed URL
get_args = parsed_url.query
# Converting URL arguments to dict
parsed_get_args = dict(parse_qsl(get_args))
# Merging URL arguments dict with new params
parsed_get_args.update(params)
# Bool and Dict values should be converted to json-friendly values
# you may throw this part away if you don't like it :)
parsed_get_args.update(
{k: dumps(v) for k, v in parsed_get_args.items()
if isinstance(v, (bool, dict))}
)
# Converting URL argument to proper query string
encoded_get_args = urlencode(parsed_get_args, doseq=True)
# Creating new parsed result object based on provided with new
# URL arguments. Same thing happens inside of urlparse.
new_url = ParseResult(
parsed_url.scheme, parsed_url.netloc, parsed_url.path,
parsed_url.params, encoded_get_args, parsed_url.fragment
).geturl()
return new_url
def get_url(self):
url = self.url
for type in self.types:
try:
value = self.opts[type]
except:
continue
if type == "labels" or type == "projects":
if not isinstance(value, list):
err = "The {0} option should be an array".format(type)
raise TypeError(err)
value = ",".join(map(str, value))
self.opts[type] = value
self.url = self.add_url_params(url, self.opts)
return self.url
def opn(self):
webbrowser.open(self.get_url(), 1)
| {"/test.py": ["/new_github_issue_url.py"]} |
57,333 | blazemits/qpayserver | refs/heads/master | /SignUp/views.py | from rest_framework import viewsets
from SignUp.serializers import Bank_Serializer,Wallet_Serializer,User_Serializer
from SignUp.models import wallet_table,bank_table,user_table
"""
class main_view(viewsets.ModelViewSet):
queryset =bank_table.objects.all()
serializer_class = Bank_Serializer
"""
class Wallet_View_Sets(viewsets.ModelViewSet):
queryset = wallet_table.objects.all()
serializer_class = Wallet_Serializer
class Bank_View_Sets(viewsets.ModelViewSet):
queryset = bank_table.objects.all()
serializer_class = Bank_Serializer
class User_View_Sets(viewsets.ModelViewSet):
queryset = user_table.objects.all()
serializer_class = User_Serializer | {"/SignUp/views.py": ["/SignUp/serializers.py", "/SignUp/models.py"], "/Qpay_REST/urls.py": ["/Qpay_REST/views.py", "/SignUp/views.py", "/login_app/views.py"], "/login_app/views.py": ["/login_app/serializers.py", "/login_app/models.py"], "/login_app/admin.py": ["/login_app/models.py"], "/SignUp/serializers.py": ["/SignUp/models.py"], "/SignUp/admin.py": ["/SignUp/models.py"], "/login_app/serializers.py": ["/login_app/models.py"]} |
57,334 | blazemits/qpayserver | refs/heads/master | /Qpay_REST/views.py | from django.http import HttpResponse
def home(request):
return HttpResponse("Qpay Home page \n Test By JpG ")
def api_page(request):
return HttpResponse("Qpay api_page \n Test By JpG ") | {"/SignUp/views.py": ["/SignUp/serializers.py", "/SignUp/models.py"], "/Qpay_REST/urls.py": ["/Qpay_REST/views.py", "/SignUp/views.py", "/login_app/views.py"], "/login_app/views.py": ["/login_app/serializers.py", "/login_app/models.py"], "/login_app/admin.py": ["/login_app/models.py"], "/SignUp/serializers.py": ["/SignUp/models.py"], "/SignUp/admin.py": ["/SignUp/models.py"], "/login_app/serializers.py": ["/login_app/models.py"]} |
57,335 | blazemits/qpayserver | refs/heads/master | /Qpay_REST/urls.py | from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers,viewsets,serializers
from Qpay_REST.views import home, api_page
from SignUp.views import Bank_View_Sets,User_View_Sets,Wallet_View_Sets
from login_app.views import Login_View_Sets
#Routers
Main_router = routers.SimpleRouter()
Main_router.register(r'login', Login_View_Sets)
Main_router.register(r'signup/bank',Bank_View_Sets)
Main_router.register(r'signup/wallet',Wallet_View_Sets)
Main_router.register(r'signup/user',User_View_Sets)
urlpatterns = [
url(r'^$',home),
url(r'^api/$',api_page),
url(r'^api/', include(Main_router.urls)),
url(r'^admin/', admin.site.urls),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
| {"/SignUp/views.py": ["/SignUp/serializers.py", "/SignUp/models.py"], "/Qpay_REST/urls.py": ["/Qpay_REST/views.py", "/SignUp/views.py", "/login_app/views.py"], "/login_app/views.py": ["/login_app/serializers.py", "/login_app/models.py"], "/login_app/admin.py": ["/login_app/models.py"], "/SignUp/serializers.py": ["/SignUp/models.py"], "/SignUp/admin.py": ["/SignUp/models.py"], "/login_app/serializers.py": ["/login_app/models.py"]} |
57,336 | blazemits/qpayserver | refs/heads/master | /login_app/models.py | from django.db import models
class Login_Model(models.Model):
id=models.IntegerField(max_length=10,auto_created=True,primary_key=True)
name=models.CharField(max_length=20)
pwd=models.CharField(max_length=20)
def __unicode__(self):
return self.id,self.name,self.pwd | {"/SignUp/views.py": ["/SignUp/serializers.py", "/SignUp/models.py"], "/Qpay_REST/urls.py": ["/Qpay_REST/views.py", "/SignUp/views.py", "/login_app/views.py"], "/login_app/views.py": ["/login_app/serializers.py", "/login_app/models.py"], "/login_app/admin.py": ["/login_app/models.py"], "/SignUp/serializers.py": ["/SignUp/models.py"], "/SignUp/admin.py": ["/SignUp/models.py"], "/login_app/serializers.py": ["/login_app/models.py"]} |
57,337 | blazemits/qpayserver | refs/heads/master | /login_app/views.py | from rest_framework import viewsets
from login_app.serializers import Login_Serializer
from login_app.models import Login_Model
class Login_View_Sets(viewsets.ModelViewSet):
queryset = Login_Model.objects.all()
serializer_class = Login_Serializer | {"/SignUp/views.py": ["/SignUp/serializers.py", "/SignUp/models.py"], "/Qpay_REST/urls.py": ["/Qpay_REST/views.py", "/SignUp/views.py", "/login_app/views.py"], "/login_app/views.py": ["/login_app/serializers.py", "/login_app/models.py"], "/login_app/admin.py": ["/login_app/models.py"], "/SignUp/serializers.py": ["/SignUp/models.py"], "/SignUp/admin.py": ["/SignUp/models.py"], "/login_app/serializers.py": ["/login_app/models.py"]} |
57,338 | blazemits/qpayserver | refs/heads/master | /login_app/admin.py | from _ast import Load
from django.contrib import admin
from login_app.models import Login_Model
admin.site.register(Login_Model)
| {"/SignUp/views.py": ["/SignUp/serializers.py", "/SignUp/models.py"], "/Qpay_REST/urls.py": ["/Qpay_REST/views.py", "/SignUp/views.py", "/login_app/views.py"], "/login_app/views.py": ["/login_app/serializers.py", "/login_app/models.py"], "/login_app/admin.py": ["/login_app/models.py"], "/SignUp/serializers.py": ["/SignUp/models.py"], "/SignUp/admin.py": ["/SignUp/models.py"], "/login_app/serializers.py": ["/login_app/models.py"]} |
57,339 | blazemits/qpayserver | refs/heads/master | /SignUp/models.py | from __future__ import unicode_literals
from django.db import models
# Create your models here.
class bank_table(models.Model):
bank_ac_num=models.IntegerField(primary_key=True)
bank_ifci_code=models.CharField(max_length=30)
user_status=models.BooleanField(default=True)
def __unicode__(self):
return "%s"%self.bank_ac_num
class wallet_table(models.Model):
mob_num=models.IntegerField(primary_key=True)
bank_ac_num=models.OneToOneField(bank_table,on_delete=models.CASCADE)
wallet_amnt=models.IntegerField(default=0)
def __unicode__(self):
return "%s"%self.mob_num
class user_table(models.Model):
user_id=models.AutoField(primary_key=True)
user_name=models.CharField(max_length=30)
mob_num=models.OneToOneField(wallet_table,null=False)
def __unicode__(self):
return "%s"%self.user_id
| {"/SignUp/views.py": ["/SignUp/serializers.py", "/SignUp/models.py"], "/Qpay_REST/urls.py": ["/Qpay_REST/views.py", "/SignUp/views.py", "/login_app/views.py"], "/login_app/views.py": ["/login_app/serializers.py", "/login_app/models.py"], "/login_app/admin.py": ["/login_app/models.py"], "/SignUp/serializers.py": ["/SignUp/models.py"], "/SignUp/admin.py": ["/SignUp/models.py"], "/login_app/serializers.py": ["/login_app/models.py"]} |
57,340 | blazemits/qpayserver | refs/heads/master | /SignUp/migrations/0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-04-18 16:26
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='bank_table',
fields=[
('bank_ac_num', models.IntegerField(primary_key=True, serialize=False)),
('bank_ifci_code', models.CharField(max_length=30)),
('user_status', models.BooleanField(default=True)),
],
),
migrations.CreateModel(
name='user_table',
fields=[
('user_id', models.AutoField(primary_key=True, serialize=False)),
('user_name', models.CharField(max_length=30)),
],
),
migrations.CreateModel(
name='wallet_table',
fields=[
('mob_num', models.IntegerField(primary_key=True, serialize=False)),
('wallet_amnt', models.IntegerField(default=0)),
('bank_ac_num', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='SignUp.bank_table')),
],
),
migrations.AddField(
model_name='user_table',
name='mob_num',
field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='SignUp.wallet_table'),
),
]
| {"/SignUp/views.py": ["/SignUp/serializers.py", "/SignUp/models.py"], "/Qpay_REST/urls.py": ["/Qpay_REST/views.py", "/SignUp/views.py", "/login_app/views.py"], "/login_app/views.py": ["/login_app/serializers.py", "/login_app/models.py"], "/login_app/admin.py": ["/login_app/models.py"], "/SignUp/serializers.py": ["/SignUp/models.py"], "/SignUp/admin.py": ["/SignUp/models.py"], "/login_app/serializers.py": ["/login_app/models.py"]} |
57,341 | blazemits/qpayserver | refs/heads/master | /SignUp/serializers.py | from rest_framework import serializers
from SignUp.models import wallet_table,bank_table,user_table
class Bank_Serializer(serializers.ModelSerializer):
class Meta:
model=bank_table
field='__all__'
#('bank_ac_num','bank_ifci_code','user_status')
class Wallet_Serializer(serializers.ModelSerializer):
bank_ac_num=Bank_Serializer(read_only=True)
class Meta:
model=wallet_table
field='__all__'
class User_Serializer(serializers.ModelSerializer):
mob_num=Wallet_Serializer(read_only=True)
class Meta:
model=user_table
field='__all__'
| {"/SignUp/views.py": ["/SignUp/serializers.py", "/SignUp/models.py"], "/Qpay_REST/urls.py": ["/Qpay_REST/views.py", "/SignUp/views.py", "/login_app/views.py"], "/login_app/views.py": ["/login_app/serializers.py", "/login_app/models.py"], "/login_app/admin.py": ["/login_app/models.py"], "/SignUp/serializers.py": ["/SignUp/models.py"], "/SignUp/admin.py": ["/SignUp/models.py"], "/login_app/serializers.py": ["/login_app/models.py"]} |
57,342 | blazemits/qpayserver | refs/heads/master | /SignUp/admin.py | from django.contrib import admin
from SignUp.models import *
# Register your models here.
admin.site.register(user_table)
admin.site.register(bank_table)
admin.site.register(wallet_table)
| {"/SignUp/views.py": ["/SignUp/serializers.py", "/SignUp/models.py"], "/Qpay_REST/urls.py": ["/Qpay_REST/views.py", "/SignUp/views.py", "/login_app/views.py"], "/login_app/views.py": ["/login_app/serializers.py", "/login_app/models.py"], "/login_app/admin.py": ["/login_app/models.py"], "/SignUp/serializers.py": ["/SignUp/models.py"], "/SignUp/admin.py": ["/SignUp/models.py"], "/login_app/serializers.py": ["/login_app/models.py"]} |
57,343 | blazemits/qpayserver | refs/heads/master | /login_app/serializers.py | from rest_framework import serializers
from login_app.models import Login_Model
class Login_Serializer(serializers.ModelSerializer):
class Meta:
model=Login_Model
field=('id','name','pwd') | {"/SignUp/views.py": ["/SignUp/serializers.py", "/SignUp/models.py"], "/Qpay_REST/urls.py": ["/Qpay_REST/views.py", "/SignUp/views.py", "/login_app/views.py"], "/login_app/views.py": ["/login_app/serializers.py", "/login_app/models.py"], "/login_app/admin.py": ["/login_app/models.py"], "/SignUp/serializers.py": ["/SignUp/models.py"], "/SignUp/admin.py": ["/SignUp/models.py"], "/login_app/serializers.py": ["/login_app/models.py"]} |
57,344 | Shangyint/ballCollisionSimulator | refs/heads/master | /container.py | import numpy as np
class Container(object):
"""
Container is either a 2d plate or a 3d box
"""
def __init__(self, args):
"""
dim should be either 2 or 3
x, y, and z are the boundaries of the container
"""
super(Container, self).__init__()
self.dimension = args[0]
self.x = args[1]
self.y = args[2]
self.lower_bound = [0, 0,]
self.upper_bound = [self.x, self.y,]
if self.dimension == 3:
self.z = args[3]
self.lower_bound.append(0)
self.upper_bound.append(self.z)
import sys
print(sys.path) | {"/main.py": ["/ball.py", "/container.py", "/graphic_client.py", "/field.py"]} |
57,345 | Shangyint/ballCollisionSimulator | refs/heads/master | /main.py | import ball, container, graphic_client, field
import numpy as np
import json, os, itertools
# import tkinter as tk
#############################
##### temp data section #####
# x_max, y_max = 1000
# dimension = 2
# ball_number = 2
# ball_a = ball()
##### only for debuging #####
#############################
def parse_json(filename):
# json_s = ""
f = open(filename, "r")
# json_s = f.read()
return json.load(f)
def find_file_name():
res = 0
while True:
if os.path.isfile("data_out" + str(res)):
res += 1
else:
return res
def init_other(input_data, data):
"""
"""
data.field = field.Field(input_data["field"])
data.time_stamp = input_data["time_stamp"]
data.time_limit = input_data["time_limit"]
data.energy_loss = -input_data["energy_loss"]
data.precision = input_data["precision"]
data.res_filename = "data_out" + str(find_file_name())
def init_container(input_data, data):
"""
"""
data.container = container.Container(input_data["container"])
def init_balls(input_data, data):
"""
"""
data.ball_list = []
for i in range(1, input_data["ball_number"] + 1):
data.ball_list.append(ball.Ball(input_data["ball"+str(i)]))
if data.field.name == "acceleration":
for ball_instance in data.ball_list:
ball_instance.acc = data.field.acc
if data.field.name == "force":
for ball_instance in data.ball_list:
ball_instance.acc = data.field.force / ball_instance.m
def run(data):
precision = data.precision
container = data.container
f = open(data.res_filename, "w")
precision_constant = 5
for run_time in range(int(data.time_limit //data.time_stamp) * precision_constant):
# update ball position
for ball in data.ball_list:
ball.update(data.time_stamp / precision_constant)
# check coordinates with the boundary of the container
for i in range(len(ball.pos)):
# check upper bound
if ball.pos[i] > container.upper_bound[i] - ball.r:
ball.v[i] *= data.energy_loss
ball.pos[i] = container.upper_bound[i] - ball.r
# print(ball.v)
# check lower bound
if ball.pos[i] < ball.r:
ball.v[i] *= data.energy_loss
ball.pos[i] = ball.r
# check for collision between balls
for pair in itertools.combinations(data.ball_list, 2):
ball1 = pair[0]
ball2 = pair[1]
pos_diff = ball1.pos - ball2.pos
# TODO
if np.linalg.norm(pos_diff) <= ball1.r + ball2.r:
# change speed
mass_total = ball1.m + ball2.m
v_norm = (np.dot((ball1.v - ball2.v), (pos_diff)) /
np.linalg.norm(pos_diff) ** 2) * pos_diff
ball1.v = ball1.v - ((2 * ball2.m) / mass_total) * v_norm
ball2.v = ball2.v + ((2 * ball1.m) / mass_total) * v_norm
if run_time % precision_constant == 0:
for ball in data.ball_list:
# print(ball.pos, ball.v)
f.write("(" + ",".join([str(round(coo, precision)) for coo in ball.pos]) + ");")
f.write("\n")
# print(data.ball_list[0].v)
# energy = 0
# for ball in data.ball_list:
# energy += (ball.v[1] ** 2) * ball.m / 2
# energy += ball.m * 10 * ball.pos[1]
# print(energy)
f.close()
def init(input_data, data):
init_container(input_data, data)
init_other(input_data, data)
init_balls(input_data, data)
def final_state_print_to_terminal(data):
pass
def main():
# filename = input()
filename = "input.json"
input_data = parse_json(filename)
class Struct(object): pass
data = Struct()
init(input_data, data)
run(data)
# if you do not want the graphics component to run
# set visualize to 0 in input.json
if data.container.dimension == 2 and input_data["visualize"] == 1:
graphic_client.run_tk(data)
final_state_print_to_terminal(data)
if __name__ == '__main__':
main()
| {"/main.py": ["/ball.py", "/container.py", "/graphic_client.py", "/field.py"]} |
57,346 | Shangyint/ballCollisionSimulator | refs/heads/master | /field.py | import numpy as np
class Field(object):
"""docstring for Field"""
def __init__(self, arg):
super(Field, self).__init__()
self.name = arg[0]
self.dim = arg[1]
self.type = arg[2]
if self.name == "force":
self.force = np.asarray(arg[3], np.double)
elif self.name == "acceleration":
self.acc = np.asarray(arg[3], np.double)
| {"/main.py": ["/ball.py", "/container.py", "/graphic_client.py", "/field.py"]} |
57,347 | Shangyint/ballCollisionSimulator | refs/heads/master | /graphic_client.py | import tkinter as tk
def _create_circle(self, x, y, r, **kwargs):
""" ref
https://stackoverflow.com/questions/17985216/draw-circle-in-tkinter-python
"""
return self.create_oval(x-r, y-r, x+r, y+r, **kwargs)
tk.Canvas.create_circle = _create_circle
def redraw_all(canvas, data):
for (i, ball) in enumerate(data.ball_list):
canvas.create_circle(ball.pos[0] * data.zoom_index,
ball.pos[1] * data.zoom_index, ball.r * data.zoom_index,
outline="", fill=data.color_list[i])
def timer_fired(data):
if not data.is_paused:
pos_info = data.f.readline().split(";")
if pos_info == [""]:
data.is_paused = True
return
# positions are stored as "(x,y,z)"
pos = [s[1:-1].split(",") for s in pos_info]
for (i, ball) in enumerate(data.ball_list):
ball.pos = list(map(float, pos[i]))
def init_zoom(data):
data.zoom_index = data.width / data.container.x
def run_tk(data, width=600, height=600):
"""
the visualization now only works with 2d collision,
and the container should be approximately square
"""
def redraw_all_wrapper(canvas, data):
canvas.delete("all")
redraw_all(canvas, data)
canvas.update()
def timer_fired_wrapper(canvas, data):
timer_fired(data)
redraw_all_wrapper(canvas, data)
# pause, then call timerFired again
canvas.after(data.timer_delay, timer_fired_wrapper, canvas, data)
# Set up data
data.width = width
data.height = height
data.timer_delay = 35 # milliseconds
data.is_paused = False
data.color_list = ["blue", "red", "yellow", "green", "red",]
init_zoom(data)
data.f = open(data.res_filename, "r")
# create the root and the canvas
root = tk.Tk()
canvas = tk.Canvas(root, width=data.width, height=data.height)
canvas.pack()
timer_fired_wrapper(canvas, data)
# and launch the app
root.mainloop() # blocks until window is closed
data.f.close() | {"/main.py": ["/ball.py", "/container.py", "/graphic_client.py", "/field.py"]} |
57,348 | Shangyint/ballCollisionSimulator | refs/heads/master | /ball.py | import numpy as np
class Ball(object):
"""
@properties
pos is position
v is velocity
r is radius
m is mass
"""
def __init__(self, args):
super(Ball, self).__init__()
self.pos = np.asarray(args[0], np.double)
self.v = np.asarray(args[1], np.double)
self.r = args[2]
self.m = args[3]
self.acc = np.asarray(args[4], np.double)
def update(self, t=1):
"""
@brief update the ball's postion based on time elapsed
@param t = timer_fired
"""
self.pos = np.add(self.pos, t * self.v + self.acc * (1/2 * t ** 2))
self.v = np.add(self.v, t * self.acc)
| {"/main.py": ["/ball.py", "/container.py", "/graphic_client.py", "/field.py"]} |
57,349 | PX4/flight_review | refs/heads/main | /app/notebook_helper.py |
def print_ulog_info(ulog):
print('System: {:}'.format(ulog.msg_info_dict['sys_name']))
if 'ver_hw' in ulog.msg_info_dict:
print('Hardware: {:}'.format(ulog.msg_info_dict['ver_hw']))
if 'ver_sw' in ulog.msg_info_dict:
print('Software Version: {:}'.format(ulog.msg_info_dict['ver_sw']))
# dropouts
dropout_durations = [ dropout.duration for dropout in ulog.dropouts]
if len(dropout_durations) > 0:
total_duration = sum(dropout_durations) / 1000
if total_duration > 5:
total_duration_str = '{:.0f}'.format(total_duration)
else:
total_duration_str = '{:.2f}'.format(total_duration)
print('Dropouts: {:} ({:} s)'.format(
len(dropout_durations), total_duration_str))
# logging duration
m, s = divmod(int((ulog.last_timestamp - ulog.start_timestamp)/1e6), 60)
h, m = divmod(m, 60)
print('Logging duration: {:d}:{:02d}:{:02d}'.format( h, m, s))
| {"/app/tornado_handlers/browse.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/radio_controller.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/edit_entry.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/upload.py": ["/app/tornado_handlers/common.py", "/app/tornado_handlers/send_email.py", "/app/tornado_handlers/multipart_streamer.py"], "/app/tornado_handlers/three_d.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/db_info_json.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/download.py": ["/app/tornado_handlers/common.py"]} |
57,350 | PX4/flight_review | refs/heads/main | /app/tornado_handlers/browse.py | """
Tornado handler for the browse page
"""
from __future__ import print_function
import collections
import sys
import os
from datetime import datetime
import json
import sqlite3
import tornado.web
# this is needed for the following imports
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../plot_app'))
from config import get_db_filename, get_overview_img_filepath
from db_entry import DBData, DBDataGenerated
from helper import flight_modes_table, get_airframe_data, html_long_word_force_break
#pylint: disable=relative-beyond-top-level,too-many-statements
from .common import get_jinja_env, get_generated_db_data_from_log
BROWSE_TEMPLATE = 'browse.html'
#pylint: disable=abstract-method
class BrowseDataRetrievalHandler(tornado.web.RequestHandler):
""" Ajax data retrieval handler """
def get(self, *args, **kwargs):
""" GET request """
search_str = self.get_argument('search[value]', '').lower()
order_ind = int(self.get_argument('order[0][column]'))
order_dir = self.get_argument('order[0][dir]', '').lower()
data_start = int(self.get_argument('start'))
data_length = int(self.get_argument('length'))
draw_counter = int(self.get_argument('draw'))
json_output = {}
json_output['draw'] = draw_counter
# get the logs (but only the public ones)
con = sqlite3.connect(get_db_filename(), detect_types=sqlite3.PARSE_DECLTYPES)
cur = con.cursor()
sql_order = ' ORDER BY Date DESC'
ordering_col = ['',#table row number
'Logs.Date',
'',#Overview - img
'Logs.Description',
'LogsGenerated.MavType',
'',#Airframe - not from DB
'LogsGenerated.Hardware',
'LogsGenerated.Software',
'LogsGenerated.Duration',
'LogsGenerated.StartTime',
'',#Rating
'LogsGenerated.NumLoggedErrors',
'' #FlightModes
]
if ordering_col[order_ind] != '':
sql_order = ' ORDER BY ' + ordering_col[order_ind]
if order_dir == 'desc':
sql_order += ' DESC'
cur.execute('SELECT Logs.Id, Logs.Date, '
' Logs.Description, Logs.WindSpeed, '
' Logs.Rating, Logs.VideoUrl, '
' LogsGenerated.* '
'FROM Logs '
' LEFT JOIN LogsGenerated on Logs.Id=LogsGenerated.Id '
'WHERE Logs.Public = 1 AND NOT Logs.Source = "CI" '
+sql_order)
# pylint: disable=invalid-name
Columns = collections.namedtuple("Columns", "columns search_only_columns")
def get_columns_from_tuple(db_tuple, counter, all_overview_imgs):
""" load the columns (list of strings) from a db_tuple
"""
db_data = DBDataJoin()
log_id = db_tuple[0]
log_date = db_tuple[1].strftime('%Y-%m-%d')
db_data.description = db_tuple[2]
db_data.feedback = ''
db_data.type = ''
db_data.wind_speed = db_tuple[3]
db_data.rating = db_tuple[4]
db_data.video_url = db_tuple[5]
generateddata_log_id = db_tuple[6]
if log_id != generateddata_log_id:
print('Join failed, loading and updating data')
db_data_gen = get_generated_db_data_from_log(log_id, con, cur)
if db_data_gen is None:
return None
db_data.add_generated_db_data_from_log(db_data_gen)
else:
db_data.duration_s = db_tuple[7]
db_data.mav_type = db_tuple[8]
db_data.estimator = db_tuple[9]
db_data.sys_autostart_id = db_tuple[10]
db_data.sys_hw = db_tuple[11]
db_data.ver_sw = db_tuple[12]
db_data.num_logged_errors = db_tuple[13]
db_data.num_logged_warnings = db_tuple[14]
db_data.flight_modes = \
{int(x) for x in db_tuple[15].split(',') if len(x) > 0}
db_data.ver_sw_release = db_tuple[16]
db_data.vehicle_uuid = db_tuple[17]
db_data.flight_mode_durations = \
[tuple(map(int, x.split(':'))) for x in db_tuple[18].split(',') if len(x) > 0]
db_data.start_time_utc = db_tuple[19]
# bring it into displayable form
ver_sw = db_data.ver_sw
if len(ver_sw) > 10:
ver_sw = ver_sw[:6]
if len(db_data.ver_sw_release) > 0:
try:
release_split = db_data.ver_sw_release.split()
release_type = int(release_split[1])
if release_type == 255: # it's a release
ver_sw = release_split[0]
except:
pass
airframe_data = get_airframe_data(db_data.sys_autostart_id)
if airframe_data is None:
airframe = db_data.sys_autostart_id
else:
airframe = airframe_data['name']
flight_modes = ', '.join([flight_modes_table[x][0]
for x in db_data.flight_modes if x in
flight_modes_table])
m, s = divmod(db_data.duration_s, 60)
h, m = divmod(m, 60)
duration_str = '{:d}:{:02d}:{:02d}'.format(h, m, s)
start_time_str = 'N/A'
if db_data.start_time_utc != 0:
try:
start_datetime = datetime.fromtimestamp(db_data.start_time_utc)
start_time_str = start_datetime.strftime("%Y-%m-%d %H:%M")
except ValueError as value_error:
# bogus date
print(value_error)
# make sure to break long descriptions w/o spaces (otherwise they
# mess up the layout)
description = html_long_word_force_break(db_data.description)
search_only_columns = []
if db_data.ver_sw is not None:
search_only_columns.append(db_data.ver_sw)
if db_data.ver_sw_release is not None:
search_only_columns.append(db_data.ver_sw_release)
if db_data.vehicle_uuid is not None:
search_only_columns.append(db_data.vehicle_uuid)
image_col = '<div class="no_map_overview"> Not rendered / No GPS </div>'
overview_image_filename = log_id+'.png'
if overview_image_filename in all_overview_imgs:
image_col = '<img class="map_overview" src="/overview_img/'
image_col += log_id+'.png" alt="Overview Image Load Failed" height=50/>'
return Columns([
counter,
'<a href="plot_app?log='+log_id+'">'+log_date+'</a>',
image_col,
description,
db_data.mav_type,
airframe,
db_data.sys_hw,
ver_sw,
duration_str,
start_time_str,
db_data.rating_str(),
db_data.num_logged_errors,
flight_modes
], search_only_columns)
# need to fetch all here, because we will do more SQL calls while
# iterating (having multiple cursor's does not seem to work)
db_tuples = cur.fetchall()
json_output['recordsTotal'] = len(db_tuples)
json_output['data'] = []
if data_length == -1:
data_length = len(db_tuples)
filtered_counter = 0
all_overview_imgs = set(os.listdir(get_overview_img_filepath()))
if search_str == '':
# speed-up the request by iterating only over the requested items
counter = data_start
for i in range(data_start, min(data_start + data_length, len(db_tuples))):
counter += 1
columns = get_columns_from_tuple(db_tuples[i], counter, all_overview_imgs)
if columns is None:
continue
json_output['data'].append(columns.columns)
filtered_counter = len(db_tuples)
else:
counter = 1
for db_tuple in db_tuples:
counter += 1
columns = get_columns_from_tuple(db_tuple, counter, all_overview_imgs)
if columns is None:
continue
if any(search_str in str(column).lower() for column in \
(columns.columns, columns.search_only_columns)):
if data_start <= filtered_counter < data_start + data_length:
json_output['data'].append(columns.columns)
filtered_counter += 1
cur.close()
con.close()
json_output['recordsFiltered'] = filtered_counter
self.set_header('Content-Type', 'application/json')
self.write(json.dumps(json_output))
class DBDataJoin(DBData, DBDataGenerated):
"""Class for joined Data"""
def add_generated_db_data_from_log(self, source):
"""Update joined data by parent data"""
self.__dict__.update(source.__dict__)
class BrowseHandler(tornado.web.RequestHandler):
""" Browse public log file Tornado request handler """
def get(self, *args, **kwargs):
""" GET request """
template = get_jinja_env().get_template(BROWSE_TEMPLATE)
template_args = {}
search_str = self.get_argument('search', '').lower()
if len(search_str) > 0:
template_args['initial_search'] = json.dumps(search_str)
self.write(template.render(template_args))
| {"/app/tornado_handlers/browse.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/radio_controller.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/edit_entry.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/upload.py": ["/app/tornado_handlers/common.py", "/app/tornado_handlers/send_email.py", "/app/tornado_handlers/multipart_streamer.py"], "/app/tornado_handlers/three_d.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/db_info_json.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/download.py": ["/app/tornado_handlers/common.py"]} |
57,351 | PX4/flight_review | refs/heads/main | /app/plot_app/config.py | """ configuration variables """
import configparser
import os
#pylint: disable=invalid-name
# load the config
_conf = configparser.ConfigParser()
_cur_dir = os.path.dirname(os.path.realpath(__file__))
_conf.read_file(open(os.path.join(_cur_dir, '../config_default.ini'), encoding='utf-8'))
_user_config_file = os.path.join(_cur_dir, '../config_user.ini')
_user_config_file_old = os.path.join(_cur_dir, '../../config_user.ini')
if os.path.exists(_user_config_file_old) and not os.path.exists(_user_config_file):
print('moving config file')
os.rename(_user_config_file_old, _user_config_file)
if os.path.exists(_user_config_file):
_conf.read_file(open(_user_config_file, encoding='utf-8'))
email_config = dict(_conf.items('email'))
email_notifications_config = dict(_conf.items('email_notifications'))
email_notifications_config['public_flightreport'] = \
[ s.strip() for s in email_notifications_config['public_flightreport'].split(',')]
email_notifications_config['public_flightreport_bad'] = \
[ s.strip() for s in email_notifications_config['public_flightreport_bad'].split(',')]
__DOMAIN_NAME = _conf.get('general', 'domain_name')
__HTTP_PROTOCOL = _conf.get('general', 'http_protocol')
__AIRFRAMES_URL = _conf.get('general', 'airframes_url')
__PARAMETERS_URL = _conf.get('general', 'parameters_url')
__EVENTS_URL = _conf.get('general', 'events_url')
__MAPBOX_API_ACCESS_TOKEN = _conf.get('general', 'mapbox_api_access_token')
__BING_API_KEY = _conf.get('general', 'bing_maps_api_key')
__CESIUM_API_KEY = _conf.get('general', 'cesium_api_key')
__LOG_CACHE_SIZE = int(_conf.get('general', 'log_cache_size'))
__DB_FILENAME_CUSTOM = _conf.get('general', 'db_filename')
__STORAGE_PATH = _conf.get('general', 'storage_path')
if not os.path.isabs(__STORAGE_PATH):
__STORAGE_PATH = os.path.join(_cur_dir, '..', __STORAGE_PATH)
__LOG_FILE_PATH = os.path.join(__STORAGE_PATH, 'log_files')
__DB_FILENAME = os.path.join(__STORAGE_PATH, 'logs.sqlite')
__CACHE_FILE_PATH = os.path.join(__STORAGE_PATH, 'cache')
__AIRFRAMES_FILENAME = os.path.join(__CACHE_FILE_PATH, 'airframes.xml')
__PARAMETERS_FILENAME = os.path.join(__CACHE_FILE_PATH, 'parameters.xml')
__EVENTS_FILENAME = os.path.join(__CACHE_FILE_PATH, 'events.json.xz')
__RELEASES_FILENAME = os.path.join(__CACHE_FILE_PATH, 'releases.json')
__METADATA_CACHE_PATH = os.path.join(__CACHE_FILE_PATH, 'metadata')
__PRINT_TIMING = int(_conf.get('debug', 'print_timing'))
__VERBOSE_OUTPUT = int(_conf.get('debug', 'verbose_output'))
# general configuration variables for plotting
plot_width = 840
plot_color_blue = '#2877a2' # or: #3539e0
plot_color_red = '#e0212d'
plot_config = {
'maps_line_color': plot_color_blue,
'plot_width': plot_width,
'plot_height': {
'normal': int(plot_width / 2.1),
'small': int(plot_width / 2.5),
'large': int(plot_width / 1.61803398874989484), # used for the gps map
},
}
colors3 = [plot_color_red, '#208900', plot_color_blue]
colors2 = [colors3[0], colors3[1]] # for data to express: 'what it is' and 'what it should be'
colors8 = [colors3[0], colors3[1], colors3[2], '#333333', '#999999', '#e58C33',
'#33e5e5', '#e533e5']
color_gray = '#464646'
plot_config['mission_setpoint_color'] = colors8[5]
def get_domain_name():
""" get configured domain name (w/o http://) """
return __DOMAIN_NAME
def get_http_protocol():
""" get the protocol: either http or https """
return __HTTP_PROTOCOL
def get_log_filepath():
""" get configured log files directory """
return __LOG_FILE_PATH
def get_cache_filepath():
""" get configured cache directory """
return __CACHE_FILE_PATH
def get_kml_filepath():
""" get configured KML files directory """
return os.path.join(get_cache_filepath(), 'kml')
def get_overview_img_filepath():
""" get configured overview image directory """
return os.path.join(get_cache_filepath(), 'img')
def get_db_filename():
""" get configured DB file name """
if __DB_FILENAME_CUSTOM != "":
return __DB_FILENAME_CUSTOM
return __DB_FILENAME
def get_airframes_filename():
""" get configured airframes file name """
return __AIRFRAMES_FILENAME
def get_airframes_url():
""" get airframes download URL """
return __AIRFRAMES_URL
def get_events_filename():
""" get configured events file name (.json.xz) """
return __EVENTS_FILENAME
def get_events_url():
""" get events download URL """
return __EVENTS_URL
def get_releases_filename():
""" get configured releases file name """
return __RELEASES_FILENAME
def get_metadata_cache_path():
""" get configured metadata cache path """
return __METADATA_CACHE_PATH
def get_parameters_filename():
""" get configured parameters file name """
return __PARAMETERS_FILENAME
def get_parameters_url():
""" get parameters download URL """
return __PARAMETERS_URL
def get_mapbox_api_access_token():
""" get MapBox API Access Token """
return __MAPBOX_API_ACCESS_TOKEN
def get_bing_maps_api_key():
""" get Bing maps API key """
return __BING_API_KEY
def get_cesium_api_key():
""" get Cesium API key """
return __CESIUM_API_KEY
def get_log_cache_size():
""" get maximum number of cached logs in RAM """
return __LOG_CACHE_SIZE
def debug_print_timing():
""" print timing information? """
return __PRINT_TIMING == 1
def debug_verbose_output():
""" print verbose output? """
return __VERBOSE_OUTPUT == 1
| {"/app/tornado_handlers/browse.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/radio_controller.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/edit_entry.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/upload.py": ["/app/tornado_handlers/common.py", "/app/tornado_handlers/send_email.py", "/app/tornado_handlers/multipart_streamer.py"], "/app/tornado_handlers/three_d.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/db_info_json.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/download.py": ["/app/tornado_handlers/common.py"]} |
57,352 | PX4/flight_review | refs/heads/main | /app/plot_app/downsampling.py | """ Class for server-side dynamic data downsampling """
from timeit import default_timer as timer
import numpy as np
from bokeh.models import ColumnDataSource
from helper import print_timing
class DynamicDownsample:
""" server-side dynamic data downsampling of bokeh time series plots
using numpy data sources.
Initializes the plot with a fixed number of samples per pixel and then
dynamically loads samples when zooming in or out based on density
thresholds.
Currently uses a very simple downsampling by picking every N-th sample
"""
def __init__(self, bokeh_plot, data, x_key):
""" Initialize and setup callback
Args:
bokeh_plot (bokeh.plotting.figure) : plot for downsampling
data (dict) : data source of the plots, contains all samples. Arrays
are expected to be numpy
x_key (str): key for x axis in data
"""
self.bokeh_plot = bokeh_plot
self.x_key = x_key
self.data = data
self.last_step_size = 1
# parameters
# minimum number of samples/pixel. Below that, we load new data
self.min_density = 2
# density on startup: density used for initializing the plot. The
# smaller this is, the less data needs to be loaded on page load (this
# must still be >= min_density).
self.startup_density = 3
# when loading new data, number of samples/pixel is set to this value
self.init_density = 5
# when loading new data, add a percentage of data on both sides
self.range_margin = 0.2
# create a copy of the initial data
self.init_data = {}
self.cur_data = {}
for k in data:
self.init_data[k] = data[k]
self.cur_data[k] = data[k]
# first downsampling
self.downsample(self.cur_data, self.bokeh_plot.plot_width *
self.startup_density)
self.data_source = ColumnDataSource(data=self.cur_data)
# register the callbacks
bokeh_plot.x_range.on_change('start', self.x_range_change_cb)
bokeh_plot.x_range.on_change('end', self.x_range_change_cb)
def x_range_change_cb(self, attr, old, new):
""" bokeh server-side callback when plot x-range changes (zooming) """
cb_start_time = timer()
new_range = [self.bokeh_plot.x_range.start, self.bokeh_plot.x_range.end]
if None in new_range:
return
plot_width = self.bokeh_plot.plot_width
init_x = self.init_data[self.x_key]
cur_x = self.cur_data[self.x_key]
cur_range = [cur_x[0], cur_x[-1]]
need_update = False
if (new_range[0] < cur_range[0] and cur_range[0] > init_x[0]) or \
(new_range[1] > cur_range[1] and cur_range[1] < init_x[-self.last_step_size]):
need_update = True # zooming out / panning
visible_points = ((new_range[0] < cur_x) & (cur_x < new_range[1])).sum()
if visible_points / plot_width < self.min_density:
visible_points_all_data = ((new_range[0] < init_x) & (init_x < new_range[1])).sum()
if visible_points_all_data > visible_points:
need_update = True
# else: reached maximum zoom level
if visible_points / plot_width > self.init_density * 3:
# mostly a precaution, the panning case above catches most cases
need_update = True
if need_update:
drange = new_range[1] - new_range[0]
new_range[0] -= drange * self.range_margin
new_range[1] += drange * self.range_margin
num_data_points = plot_width * self.init_density * (1 + 2*self.range_margin)
indices = np.logical_and(init_x > new_range[0], init_x < new_range[1])
self.cur_data = {}
for k,value in self.init_data.items():
self.cur_data[k] = value[indices]
# downsample
self.downsample(self.cur_data, num_data_points)
self.data_source.data = self.cur_data
print_timing("Data update", cb_start_time)
def downsample(self, data, max_num_data_points):
""" downsampling with a given maximum number of samples """
if len(data[self.x_key]) > max_num_data_points:
step_size = int(len(data[self.x_key]) / max_num_data_points)
self.last_step_size = step_size
for k in data:
data[k] = data[k][::step_size]
| {"/app/tornado_handlers/browse.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/radio_controller.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/edit_entry.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/upload.py": ["/app/tornado_handlers/common.py", "/app/tornado_handlers/send_email.py", "/app/tornado_handlers/multipart_streamer.py"], "/app/tornado_handlers/three_d.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/db_info_json.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/download.py": ["/app/tornado_handlers/common.py"]} |
57,353 | PX4/flight_review | refs/heads/main | /app/plot_app/helper.py | """ some helper methods that don't fit in elsewhere """
import json
from timeit import default_timer as timer
import time
import re
import os
import traceback
import sys
from functools import lru_cache
from urllib.request import urlretrieve
import xml.etree.ElementTree # airframe parsing
import shutil
import uuid
from pyulog import *
from pyulog.px4 import *
from scipy.interpolate import interp1d
from config_tables import *
from config import get_log_filepath, get_airframes_filename, get_airframes_url, \
get_parameters_filename, get_parameters_url, \
get_log_cache_size, debug_print_timing, \
get_releases_filename
#pylint: disable=line-too-long, global-variable-not-assigned,invalid-name,global-statement
def print_timing(name, start_time):
""" for debugging: print elapsed time, with start_time = timer(). """
if debug_print_timing():
print(name + " took: {:.3} s".format(timer() - start_time))
# the following is for using the plotting app locally
__log_id_is_filename = {'enable': False}
def set_log_id_is_filename(enable=False):
""" treat the log_id as filename instead of id if enable=True.
WARNING: this disables log id validation, so that all log id's are valid.
Don't use it on a live server! """
__log_id_is_filename['enable'] = enable
def _check_log_id_is_filename():
return __log_id_is_filename['enable']
def is_running_locally():
"""
Check if we run locally.
Avoid using this if possible as it makes testing more difficult
"""
# this is an approximation: it's actually only True if a log is displayed
# directly via ./serve.py -f <file.ulg>
return __log_id_is_filename['enable']
def validate_log_id(log_id):
""" Check whether the log_id has a valid form (not whether it actually
exists) """
if _check_log_id_is_filename():
return True
# we are a bit less restrictive than the actual format
if re.match(r'^[0-9a-zA-Z_-]+$', log_id):
return True
return False
def get_log_filename(log_id):
""" return the ulog file name from a log id in the form:
xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
"""
if _check_log_id_is_filename():
return log_id
return os.path.join(get_log_filepath(), log_id + '.ulg')
__last_failed_downloads = {} # dict with key=file name and a timestamp of last failed download
def download_file_maybe(filename, url):
""" download an url to filename if it does not exist or it's older than a day.
returns 0: on problem, 1: file usable, 2: file usable and was downloaded
"""
need_download = False
if os.path.exists(filename):
elapsed_sec = time.time() - os.path.getmtime(filename)
if elapsed_sec / 3600 > 24:
need_download = True
os.unlink(filename)
else:
need_download = True
if need_download:
if filename in __last_failed_downloads:
if time.time() < __last_failed_downloads[filename] + 30:
# don't try to download too often
return 0
print("Downloading "+url)
try:
# download to a temporary random file, then move to avoid race
# conditions
temp_file_name = filename+'.'+str(uuid.uuid4())
urlretrieve(url, temp_file_name)
shutil.move(temp_file_name, filename)
except Exception as e:
print("Download error: "+str(e))
__last_failed_downloads[filename] = time.time()
return 0
return 2
return 1
@lru_cache(maxsize=128)
def __get_airframe_data(airframe_id):
""" cached version of get_airframe_data()
"""
airframe_xml = get_airframes_filename()
if download_file_maybe(airframe_xml, get_airframes_url()) > 0:
try:
e = xml.etree.ElementTree.parse(airframe_xml).getroot()
for airframe_group in e.findall('airframe_group'):
for airframe in airframe_group.findall('airframe'):
if str(airframe_id) == airframe.get('id'):
ret = {'name': airframe.get('name')}
try:
ret['type'] = airframe.find('type').text
except:
pass
return ret
except:
pass
return None
__last_airframe_cache_clear_timestamp = 0
def get_airframe_data(airframe_id):
""" return a dict of aiframe data ('name' & 'type') from an autostart id.
Downloads aiframes if necessary. Returns None on error
"""
global __last_airframe_cache_clear_timestamp
current_time = time.time()
if current_time > __last_airframe_cache_clear_timestamp + 3600:
__last_airframe_cache_clear_timestamp = current_time
__get_airframe_data.cache_clear()
return __get_airframe_data(airframe_id)
def get_sw_releases():
""" return a JSON object of public releases.
Downloads releases from github if necessary. Returns None on error
"""
releases_json = get_releases_filename()
if download_file_maybe(releases_json, 'https://api.github.com/repos/PX4/Firmware/releases') > 0:
with open(releases_json, encoding='utf-8') as data_file:
return json.load(data_file)
return None
def get_default_parameters():
""" get the default parameters
:return: dict with params (key is param name, value is a dict with
'default', 'min', 'max', ...)
"""
parameters_xml = get_parameters_filename()
param_dict = {}
if download_file_maybe(parameters_xml, get_parameters_url()) > 0:
try:
e = xml.etree.ElementTree.parse(parameters_xml).getroot()
for group in e.findall('group'):
group_name = group.get('name')
try:
for param in group.findall('parameter'):
param_name = param.get('name')
param_type = param.get('type')
param_default = param.get('default')
cur_param_dict = {
'default': param_default,
'type': param_type,
'group_name': group_name,
}
try:
cur_param_dict['min'] = param.find('min').text
except:
pass
try:
cur_param_dict['max'] = param.find('max').text
except:
pass
try:
cur_param_dict['short_desc'] = param.find('short_desc').text
except:
pass
try:
cur_param_dict['long_desc'] = param.find('long_desc').text
except:
pass
try:
cur_param_dict['decimal'] = param.find('decimal').text
except:
pass
param_dict[param_name] = cur_param_dict
except:
pass
except:
pass
return param_dict
def WGS84_to_mercator(lon, lat):
""" Convert lon, lat in [deg] to Mercator projection """
# alternative that relies on the pyproj library:
# import pyproj # GPS coordinate transformations
# wgs84 = pyproj.Proj('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')
# mercator = pyproj.Proj('+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 ' +
# '+lon_0=0.0 +x_0=0.0 +y_0=0 +units=m +k=1.0 +nadgrids=@null +no_defs')
# return pyproj.transform(wgs84, mercator, lon, lat)
semimajor_axis = 6378137.0 # WGS84 spheriod semimajor axis
east = lon * 0.017453292519943295
north = lat * 0.017453292519943295
northing = 3189068.5 * np.log((1.0 + np.sin(north)) / (1.0 - np.sin(north)))
easting = semimajor_axis * east
return easting, northing
def map_projection(lat, lon, anchor_lat, anchor_lon):
""" convert lat, lon in [rad] to x, y in [m] with an anchor position """
sin_lat = np.sin(lat)
cos_lat = np.cos(lat)
cos_d_lon = np.cos(lon - anchor_lon)
sin_anchor_lat = np.sin(anchor_lat)
cos_anchor_lat = np.cos(anchor_lat)
arg = sin_anchor_lat * sin_lat + cos_anchor_lat * cos_lat * cos_d_lon
arg[arg > 1] = 1
arg[arg < -1] = -1
np.set_printoptions(threshold=sys.maxsize)
c = np.arccos(arg)
k = np.copy(lat)
for i in range(len(lat)):
if np.abs(c[i]) < np.finfo(float).eps:
k[i] = 1
else:
k[i] = c[i] / np.sin(c[i])
CONSTANTS_RADIUS_OF_EARTH = 6371000
x = k * (cos_anchor_lat * sin_lat - sin_anchor_lat * cos_lat * cos_d_lon) * \
CONSTANTS_RADIUS_OF_EARTH
y = k * cos_lat * np.sin(lon - anchor_lon) * CONSTANTS_RADIUS_OF_EARTH
return x, y
def html_long_word_force_break(text, max_length=15):
"""
force line breaks for text that contains long words, suitable for HTML
display
"""
ret = ''
for d in text.split(' '):
while len(d) > max_length:
ret += d[:max_length]+'<wbr />'
d = d[max_length:]
ret += d+' '
if len(ret) > 0:
return ret[:-1]
return ret
def validate_url(url):
"""
check if valid url provided
:return: True if valid, False otherwise
"""
# source: http://stackoverflow.com/questions/7160737/python-how-to-validate-a-url-in-python-malformed-or-not
regex = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
r'localhost|' #localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
return regex.match(url) is not None
class ULogException(Exception):
"""
Exception to indicate an ULog parsing error. It is most likely a corrupt log
file, but could also be a bug in the parser.
"""
pass
@lru_cache(maxsize=get_log_cache_size())
def load_ulog_file(file_name):
""" load an ULog file
:return: ULog object
"""
# The reason to put this method into helper is that the main module gets
# (re)loaded on each page request. Thus the caching would not work there.
# load only the messages we really need
msg_filter = ['battery_status', 'distance_sensor', 'estimator_status',
'sensor_combined', 'cpuload',
'vehicle_gps_position', 'vehicle_local_position',
'vehicle_local_position_setpoint',
'vehicle_global_position', 'actuator_controls_0',
'actuator_controls_1', 'actuator_outputs',
'vehicle_angular_velocity', 'vehicle_attitude', 'vehicle_attitude_setpoint',
'vehicle_rates_setpoint', 'rc_channels',
'position_setpoint_triplet', 'vehicle_attitude_groundtruth',
'vehicle_local_position_groundtruth', 'vehicle_visual_odometry',
'vehicle_status', 'airspeed', 'airspeed_validated', 'manual_control_setpoint',
'rate_ctrl_status', 'vehicle_air_data',
'vehicle_magnetometer', 'system_power', 'tecs_status',
'sensor_baro', 'sensor_accel', 'sensor_accel_fifo',
'sensor_gyro_fifo', 'vehicle_angular_acceleration',
'ekf2_timestamps', 'manual_control_switches', 'event',
'vehicle_imu_status', 'actuator_motors', 'actuator_servos',
'vehicle_thrust_setpoint', 'vehicle_torque_setpoint',
'failsafe_flags']
try:
ulog = ULog(file_name, msg_filter, disable_str_exceptions=False)
except FileNotFoundError:
print("Error: file %s not found" % file_name)
raise
# catch all other exceptions and turn them into an ULogException
except Exception as error:
traceback.print_exception(*sys.exc_info())
raise ULogException() from error
# filter messages with timestamp = 0 (these are invalid).
# The better way is not to publish such messages in the first place, and fix
# the code instead (it goes against the monotonicity requirement of ulog).
# So we display the values such that the problem becomes visible.
# for d in ulog.data_list:
# t = d.data['timestamp']
# non_zero_indices = t != 0
# if not np.all(non_zero_indices):
# d.data = np.compress(non_zero_indices, d.data, axis=0)
return ulog
class ActuatorControls:
"""
Compatibility for actuator control topics
"""
def __init__(self, ulog, use_dynamic_control_alloc, instance=0):
self._thrust_x = None
self._thrust_z_neg = None
if use_dynamic_control_alloc:
self._topic_instance = instance
self._torque_sp_topic = 'vehicle_torque_setpoint'
self._thrust_sp_topic = 'vehicle_thrust_setpoint'
self._torque_axes_field_names = ['xyz[0]', 'xyz[1]', 'xyz[2]']
try:
# thrust is always instance 0
thrust_sp = ulog.get_dataset('vehicle_thrust_setpoint', 0)
self._thrust = np.sqrt(thrust_sp.data['xyz[0]']**2 + \
thrust_sp.data['xyz[1]']**2 + thrust_sp.data['xyz[2]']**2)
self._thrust_x = thrust_sp.data['xyz[0]']
self._thrust_z_neg = -thrust_sp.data['xyz[2]']
if instance != 0: # We must resample thrust to the desired instance
def _resample(time_array, data, desired_time):
""" resample data at a given time to a vector of desired_time """
data_f = interp1d(time_array, data, fill_value='extrapolate')
return data_f(desired_time)
thrust_sp_instance = ulog.get_dataset('vehicle_thrust_setpoint', instance)
self._thrust = _resample(thrust_sp.data['timestamp'], self._thrust,
thrust_sp_instance.data['timestamp'])
self._thrust_x = _resample(thrust_sp.data['timestamp'], self._thrust_x,
thrust_sp_instance.data['timestamp'])
self._thrust_z_neg = _resample(thrust_sp.data['timestamp'], self._thrust_z_neg,
thrust_sp_instance.data['timestamp'])
except:
self._thrust = None
else:
self._topic_instance = 0
self._torque_sp_topic = 'actuator_controls_'+str(instance)
self._thrust_sp_topic = 'actuator_controls_'+str(instance)
self._torque_axes_field_names = ['control[0]', 'control[1]', 'control[2]']
try:
torque_sp = ulog.get_dataset(self._torque_sp_topic)
self._thrust = torque_sp.data['control[3]']
if instance == 0:
# for FW this would be in X direction
self._thrust_z_neg = torque_sp.data['control[3]']
else:
self._thrust_x = torque_sp.data['control[3]']
except:
self._thrust = None
@property
def topic_instance(self):
""" get the topic instance """
return self._topic_instance
@property
def torque_sp_topic(self):
""" get the torque setpoint topic name """
return self._torque_sp_topic
@property
def thrust_sp_topic(self):
""" get the thrust setpoint topic name """
return self._thrust_sp_topic
@property
def torque_axes_field_names(self):
""" get the list of axes field names for roll, pitch and yaw """
return self._torque_axes_field_names
@property
def thrust(self):
""" get the thrust data (norm) """
return self._thrust
@property
def thrust_x(self):
""" get the thrust data in x dir """
return self._thrust_x
@property
def thrust_z_neg(self):
""" get the thrust data in -z dir """
return self._thrust_z_neg
def get_lat_lon_alt_deg(ulog: ULog, vehicle_gps_position_dataset: ULog.Data):
"""
Get (lat, lon, alt) tuple in degrees and altitude in meters
"""
if ulog.msg_info_dict.get('ver_data_format', 0) >= 2:
lat = vehicle_gps_position_dataset.data['latitude_deg']
lon = vehicle_gps_position_dataset.data['longitude_deg']
alt = vehicle_gps_position_dataset.data['altitude_msl_m']
else: # COMPATIBILITY
lat = vehicle_gps_position_dataset.data['lat'] / 1e7
lon = vehicle_gps_position_dataset.data['lon'] / 1e7
alt = vehicle_gps_position_dataset.data['alt'] / 1e3
return lat, lon, alt
def get_airframe_name(ulog, multi_line=False):
"""
get the airframe name and autostart ID.
:return: tuple (airframe name & type (str), autostart ID (str)) or None if no
autostart ID
"""
if 'SYS_AUTOSTART' in ulog.initial_parameters:
sys_autostart = ulog.initial_parameters['SYS_AUTOSTART']
airframe_data = get_airframe_data(sys_autostart)
if airframe_data is None:
return ("", str(sys_autostart))
airframe_type = ''
if multi_line:
separator = '<br>'
else:
separator = ', '
if 'type' in airframe_data:
airframe_type = separator+airframe_data['type']
return (airframe_data.get('name')+ airframe_type, str(sys_autostart))
return None
def get_total_flight_time(ulog):
"""
get the total flight time from an ulog in seconds
:return: integer or None if not set
"""
if ('LND_FLIGHT_T_HI' in ulog.initial_parameters and
'LND_FLIGHT_T_LO' in ulog.initial_parameters):
high = ulog.initial_parameters['LND_FLIGHT_T_HI']
if high < 0: # both are signed int32
high += 2**32
low = ulog.initial_parameters['LND_FLIGHT_T_LO']
if low < 0:
low += 2**32
flight_time_s = ((high << 32) | low) / 1e6
return flight_time_s
return None
def get_flight_mode_changes(ulog):
"""
get a list of flight mode changes
:return: list of (timestamp, int mode) tuples, the last is the last log
timestamp and mode = -1.
"""
try:
cur_dataset = ulog.get_dataset('vehicle_status')
flight_mode_changes = cur_dataset.list_value_changes('nav_state')
flight_mode_changes.append((ulog.last_timestamp, -1))
except (KeyError, IndexError) as error:
flight_mode_changes = []
return flight_mode_changes
def print_cache_info():
""" print information about the ulog cache """
print(load_ulog_file.cache_info())
def clear_ulog_cache():
""" clear/invalidate the ulog cache """
load_ulog_file.cache_clear()
def validate_error_ids(err_ids):
"""
validate the err_ids
"""
for err_id in err_ids:
if err_id not in error_labels_table:
return False
return True
| {"/app/tornado_handlers/browse.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/radio_controller.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/edit_entry.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/upload.py": ["/app/tornado_handlers/common.py", "/app/tornado_handlers/send_email.py", "/app/tornado_handlers/multipart_streamer.py"], "/app/tornado_handlers/three_d.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/db_info_json.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/download.py": ["/app/tornado_handlers/common.py"]} |
57,354 | PX4/flight_review | refs/heads/main | /app/plot_app/plotted_tables.py | """ methods to generate various tables used in configured_plots.py """
from html import escape
from math import sqrt
import datetime
import numpy as np
from bokeh.layouts import column
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import DataTable, TableColumn, Div, HTMLTemplateFormatter
from config import plot_color_red
from helper import (
get_default_parameters, get_airframe_name,
get_total_flight_time, error_labels_table
)
from events import get_logged_events
#pylint: disable=consider-using-enumerate,too-many-statements
def _get_vtol_means_per_mode(vtol_states, timestamps, data):
"""
get the mean values separated by MC and FW mode for some
data vector
:return: tuple of (mean mc, mean fw)
"""
vtol_state_index = 0
current_vtol_state = -1
sum_mc = 0
counter_mc = 0
sum_fw = 0
counter_fw = 0
for i in range(len(timestamps)):
if timestamps[i] > vtol_states[vtol_state_index][0]:
current_vtol_state = vtol_states[vtol_state_index][1]
vtol_state_index += 1
if current_vtol_state == 2: # FW
sum_fw += data[i]
counter_fw += 1
elif current_vtol_state == 3: # MC
sum_mc += data[i]
counter_mc += 1
mean_mc = None
if counter_mc > 0: mean_mc = sum_mc / counter_mc
mean_fw = None
if counter_fw > 0: mean_fw = sum_fw / counter_fw
return (mean_mc, mean_fw)
def get_heading_html(ulog, px4_ulog, db_data, link_to_3d_page,
additional_links=None, title_suffix=''):
"""
Get the html (as string) for the heading information (plots title)
:param additional_links: list of (label, link) tuples
"""
sys_name = ''
if 'sys_name' in ulog.msg_info_dict:
sys_name = escape(ulog.msg_info_dict['sys_name']) + ' '
if link_to_3d_page is not None and \
any(elem.name == 'vehicle_gps_position' for elem in ulog.data_list):
link_to_3d = ("<a class='btn btn-outline-primary' href='"+
link_to_3d_page+"'>Open 3D View</a>")
else:
link_to_3d = ''
added_links = ''
if additional_links is not None:
for label, link in additional_links:
added_links += ("<a class='btn btn-outline-primary' href='"+
link+"'>"+label+"</a>")
if title_suffix != '': title_suffix = ' - ' + title_suffix
title_html = ("<table width='100%'><tr><td><h3>"+sys_name + px4_ulog.get_mav_type()+
title_suffix+"</h3></td><td align='right'>" + link_to_3d +
added_links+"</td></tr></table>")
if db_data.description != '':
title_html += "<h5>"+db_data.description+"</h5>"
return title_html
def get_info_table_html(ulog, px4_ulog, db_data, vehicle_data, vtol_states):
"""
Get the html (as string) for a table with additional text info,
such as logging duration, max speed etc.
"""
### Setup the text for the left table with various information ###
table_text_left = []
# airframe
airframe_name_tuple = get_airframe_name(ulog, True)
if airframe_name_tuple is not None:
airframe_name, airframe_id = airframe_name_tuple
if len(airframe_name) == 0:
table_text_left.append(('Airframe', airframe_id))
else:
table_text_left.append(('Airframe', airframe_name+' <small>('+airframe_id+')</small>'))
# HW & SW
sys_hardware = ''
if 'ver_hw' in ulog.msg_info_dict:
sys_hardware = escape(ulog.msg_info_dict['ver_hw'])
if 'ver_hw_subtype' in ulog.msg_info_dict:
sys_hardware += ' (' + escape(ulog.msg_info_dict['ver_hw_subtype']) + ')'
table_text_left.append(('Hardware', sys_hardware))
release_str = ulog.get_version_info_str()
if release_str is None:
release_str = ''
release_str_suffix = ''
else:
release_str += ' <small>('
release_str_suffix = ')</small>'
branch_info = ''
if 'ver_sw_branch' in ulog.msg_info_dict:
branch_info = '<br> branch: '+ulog.msg_info_dict['ver_sw_branch']
if 'ver_sw' in ulog.msg_info_dict:
ver_sw = escape(ulog.msg_info_dict['ver_sw'])
ver_sw_link = 'https://github.com/PX4/Firmware/commit/'+ver_sw
table_text_left.append(('Software Version', release_str +
'<a href="'+ver_sw_link+'" target="_blank">'+ver_sw[:8]+'</a>'+
release_str_suffix+branch_info))
if 'sys_os_name' in ulog.msg_info_dict and 'sys_os_ver_release' in ulog.msg_info_dict:
os_name = escape(ulog.msg_info_dict['sys_os_name'])
os_ver = ulog.get_version_info_str('sys_os_ver_release')
if os_ver is not None:
table_text_left.append(('OS Version', os_name + ', ' + os_ver))
table_text_left.append(('Estimator', px4_ulog.get_estimator()))
table_text_left.append(('', '')) # spacing
# logging start time & date
try:
# get the first non-zero timestamp
gps_data = ulog.get_dataset('vehicle_gps_position')
indices = np.nonzero(gps_data.data['time_utc_usec'])
if len(indices[0]) > 0:
# we use the timestamp from the log and then convert it with JS to
# display with local timezone.
# In addition we add a tooltip to show the timezone from the log
logging_start_time = int(gps_data.data['time_utc_usec'][indices[0][0]] / 1000000)
utc_offset_min = ulog.initial_parameters.get('SDLOG_UTC_OFFSET', 0)
utctimestamp = datetime.datetime.utcfromtimestamp(
logging_start_time+utc_offset_min*60).replace(tzinfo=datetime.timezone.utc)
tooltip = '''This is your local timezone.
<br />
Log timezone: {}
<br />
SDLOG_UTC_OFFSET: {}'''.format(utctimestamp.strftime('%d-%m-%Y %H:%M'), utc_offset_min)
tooltip = 'data-toggle="tooltip" data-delay=\'{"show":0, "hide":100}\' '+ \
'title="'+tooltip+'" '
table_text_left.append(
('Logging Start '+
'<i '+tooltip+' class="fa fa-question" aria-hidden="true" '+
'style="font-size: larger; color:#666"></i>',
'<span style="display:none" id="logging-start-element">'+
str(logging_start_time)+'</span>'))
except:
# Ignore. Eg. if topic not found
pass
# logging duration
m, s = divmod(int((ulog.last_timestamp - ulog.start_timestamp)/1e6), 60)
h, m = divmod(m, 60)
table_text_left.append(('Logging Duration', '{:d}:{:02d}:{:02d}'.format(h, m, s)))
# dropouts
dropout_durations = [dropout.duration for dropout in ulog.dropouts]
if len(dropout_durations) > 0:
total_duration = sum(dropout_durations) / 1000
if total_duration > 5:
total_duration_str = '{:.0f}'.format(total_duration)
else:
total_duration_str = '{:.2f}'.format(total_duration)
table_text_left.append(('Dropouts', '{:} ({:} s)'.format(
len(dropout_durations), total_duration_str)))
# total vehicle flight time
flight_time_s = get_total_flight_time(ulog)
if flight_time_s is not None:
m, s = divmod(int(flight_time_s), 60)
h, m = divmod(m, 60)
days, h = divmod(h, 24)
flight_time_str = ''
if days > 0: flight_time_str += '{:d} days '.format(days)
if h > 0: flight_time_str += '{:d} hours '.format(h)
if m > 0: flight_time_str += '{:d} minutes '.format(m)
flight_time_str += '{:d} seconds '.format(s)
table_text_left.append(('Vehicle Life<br/>Flight Time', flight_time_str))
table_text_left.append(('', '')) # spacing
# vehicle UUID (and name if provided). SITL does not have a (valid) UUID
if 'sys_uuid' in ulog.msg_info_dict and sys_hardware != 'SITL' and \
sys_hardware != 'PX4_SITL':
sys_uuid = escape(ulog.msg_info_dict['sys_uuid'])
if vehicle_data is not None and vehicle_data.name != '':
sys_uuid = sys_uuid + ' (' + vehicle_data.name + ')'
if len(sys_uuid) > 0:
table_text_left.append(('Vehicle UUID', sys_uuid))
table_text_left.append(('', '')) # spacing
# Wind speed, rating, feedback
if db_data.wind_speed >= 0:
table_text_left.append(('Wind Speed', db_data.wind_speed_str()))
if len(db_data.rating) > 0:
table_text_left.append(('Flight Rating', db_data.rating_str()))
if len(db_data.feedback) > 0:
table_text_left.append(('Feedback', db_data.feedback.replace('\n', '<br/>')))
if len(db_data.video_url) > 0:
table_text_left.append(('Video', '<a href="'+db_data.video_url+
'" target="_blank">'+db_data.video_url+'</a>'))
### Setup the text for the right table: estimated numbers (e.g. max speed) ###
table_text_right = []
try:
local_pos = ulog.get_dataset('vehicle_local_position')
pos_x = local_pos.data['x']
pos_y = local_pos.data['y']
pos_z = local_pos.data['z']
pos_xyz_valid = np.multiply(local_pos.data['xy_valid'], local_pos.data['z_valid'])
local_vel_valid_indices = np.argwhere(np.multiply(local_pos.data['v_xy_valid'],
local_pos.data['v_z_valid']) > 0)
vel_x = local_pos.data['vx'][local_vel_valid_indices]
vel_y = local_pos.data['vy'][local_vel_valid_indices]
vel_z = local_pos.data['vz'][local_vel_valid_indices]
# total distance (take only valid indexes)
total_dist_m = 0
last_index = -2
for valid_index in np.argwhere(pos_xyz_valid > 0):
index = valid_index[0]
if index == last_index + 1:
dx = pos_x[index] - pos_x[last_index]
dy = pos_y[index] - pos_y[last_index]
dz = pos_z[index] - pos_z[last_index]
total_dist_m += sqrt(dx*dx + dy*dy + dz*dz)
last_index = index
if total_dist_m < 1:
pass # ignore
elif total_dist_m > 1000:
table_text_right.append(('Distance', "{:.2f} km".format(total_dist_m/1000)))
else:
table_text_right.append(('Distance', "{:.1f} m".format(total_dist_m)))
if len(pos_z) > 0:
max_alt_diff = np.amax(pos_z) - np.amin(pos_z)
table_text_right.append(('Max Altitude Difference', "{:.0f} m".format(max_alt_diff)))
table_text_right.append(('', '')) # spacing
# Speed
if len(vel_x) > 0:
max_h_speed = np.amax(np.sqrt(np.square(vel_x) + np.square(vel_y)))
speed_vector = np.sqrt(np.square(vel_x) + np.square(vel_y) + np.square(vel_z))
max_speed = np.amax(speed_vector)
if vtol_states is None:
mean_speed = np.mean(speed_vector)
table_text_right.append(('Average Speed', "{:.1f} km/h".format(mean_speed*3.6)))
else:
local_pos_timestamp = local_pos.data['timestamp'][local_vel_valid_indices]
speed_vector = speed_vector.reshape((len(speed_vector),))
mean_speed_mc, mean_speed_fw = _get_vtol_means_per_mode(
vtol_states, local_pos_timestamp, speed_vector)
if mean_speed_mc is not None:
table_text_right.append(
('Average Speed MC', "{:.1f} km/h".format(mean_speed_mc*3.6)))
if mean_speed_fw is not None:
table_text_right.append(
('Average Speed FW', "{:.1f} km/h".format(mean_speed_fw*3.6)))
table_text_right.append(('Max Speed', "{:.1f} km/h".format(max_speed*3.6)))
table_text_right.append(('Max Speed Horizontal', "{:.1f} km/h".format(max_h_speed*3.6)))
table_text_right.append(('Max Speed Up', "{:.1f} km/h".format(np.amax(-vel_z)*3.6)))
table_text_right.append(('Max Speed Down', "{:.1f} km/h".format(-np.amin(-vel_z)*3.6)))
table_text_right.append(('', '')) # spacing
vehicle_attitude = ulog.get_dataset('vehicle_attitude')
roll = vehicle_attitude.data['roll']
pitch = vehicle_attitude.data['pitch']
if len(roll) > 0:
# tilt = angle between [0,0,1] and [0,0,1] rotated by roll and pitch
tilt_angle = np.arccos(np.multiply(np.cos(pitch), np.cos(roll)))*180/np.pi
table_text_right.append(('Max Tilt Angle', "{:.1f} deg".format(np.amax(tilt_angle))))
rollspeed = vehicle_attitude.data['rollspeed']
pitchspeed = vehicle_attitude.data['pitchspeed']
yawspeed = vehicle_attitude.data['yawspeed']
if len(rollspeed) > 0:
max_rot_speed = np.amax(np.sqrt(np.square(rollspeed) +
np.square(pitchspeed) +
np.square(yawspeed)))
table_text_right.append(('Max Rotation Speed', "{:.1f} deg/s".format(
max_rot_speed*180/np.pi)))
table_text_right.append(('', '')) # spacing
battery_status = ulog.get_dataset('battery_status')
battery_current = battery_status.data['current_a']
if len(battery_current) > 0:
max_current = np.amax(battery_current)
if max_current > 0.1:
if vtol_states is None:
mean_current = np.mean(battery_current)
table_text_right.append(('Average Current', "{:.1f} A".format(mean_current)))
else:
mean_current_mc, mean_current_fw = _get_vtol_means_per_mode(
vtol_states, battery_status.data['timestamp'], battery_current)
if mean_current_mc is not None:
table_text_right.append(
('Average Current MC', "{:.1f} A".format(mean_current_mc)))
if mean_current_fw is not None:
table_text_right.append(
('Average Current FW', "{:.1f} A".format(mean_current_fw)))
table_text_right.append(('Max Current', "{:.1f} A".format(max_current)))
except:
pass # ignore (e.g. if topic not found)
# generate the tables
def generate_html_table(rows_list, tooltip=None, max_width=None):
"""
return the html table (str) from a row list of tuples
"""
if tooltip is None:
tooltip = ''
else:
tooltip = 'data-toggle="tooltip" data-placement="left" '+ \
'data-delay=\'{"show": 1000, "hide": 100}\' title="'+tooltip+'" '
table = '<table '+tooltip
if max_width is not None:
table += ' style="max-width: '+max_width+';"'
table += '>'
padding_text = ''
for label, value in rows_list:
if label == '': # empty label means: add some row spacing
padding_text = ' style="padding-top: 0.5em;" '
else:
table += ('<tr><td '+padding_text+'class="left">'+label+
':</td><td'+padding_text+'>'+value+'</td></tr>')
padding_text = ''
return table + '</table>'
left_table = generate_html_table(table_text_left, max_width='65%')
right_table = generate_html_table(
table_text_right,
'Note: most of these values are based on estimations from the vehicle,'
' and thus require an accurate estimator')
html_tables = ('<p><div style="display: flex; justify-content: space-between;">'+
left_table+right_table+'</div></p>')
return html_tables
def get_error_labels_html():
"""
Get the html (as string) for user-selectable error labels
"""
error_label_select = \
'<select id="error-label" class="chosen-select" multiple="True" '\
'style="display: none; " tabindex="-1" ' \
'data-placeholder="Add a detected error..." " >'
for err_id, err_label in error_labels_table.items():
error_label_select += '<option data-id="{:d}">{:s}</option>'.format(err_id, err_label)
error_label_select = '<p>' + error_label_select + '</select></p>'
return error_label_select
def get_corrupt_log_html(ulog):
"""
Get the html (as string) for corrupt logs,
if the log is corrupt, otherwise returns None
"""
if ulog.file_corruption:
corrupt_log_html = """
<div class="card text-white bg-danger mb-3">
<div class="card-header">Warning</div>
<div class="card-body">
<h4 class="card-title">Corrupt Log File</h4>
<p class="card-text">
This log contains corrupt data. Some of the shown data might be wrong
and some data might be missing.
<br />
A possible cause is a corrupt file system and exchanging or reformatting
the SD card fixes the problem.
</p>
</div>
</div>
"""
return corrupt_log_html
return None
def get_hardfault_html(ulog):
"""
Get the html (as string) for hardfault information,
if the log contains any, otherwise returns None
"""
if 'hardfault_plain' in ulog.msg_info_multiple_dict:
hardfault_html = """
<div class="card text-white bg-danger mb-3">
<div class="card-header">Warning</div>
<div class="card-body">
<h4 class="card-title">Software Crash</h4>
<p class="card-text">
This log contains hardfault data from a software crash
(see <a style="color:#fff; text-decoration: underline;"
href="https://docs.px4.io/master/en/debug/gdb_debugging.html#hard-fault-debugging">
here</a> how to debug).
<br/>
The hardfault data is shown below.
</p>
</div>
</div>
"""
counter = 1
for hardfault in ulog.msg_info_multiple_dict['hardfault_plain']:
hardfault_text = escape(''.join(hardfault)).replace('\n', '<br/>')
hardfault_html += ('<p>Hardfault #'+str(counter)+':<br/><pre>'+
hardfault_text+'</pre></p>')
counter += 1
return hardfault_html
return None
def get_changed_parameters(ulog, plot_width):
"""
get a bokeh column object with a table of the changed parameters
:param initial_parameters: ulog.initial_parameters
"""
param_names = []
param_values = []
param_defaults = []
param_mins = []
param_maxs = []
param_descriptions = []
param_colors = []
default_params = get_default_parameters()
initial_parameters = ulog.initial_parameters
system_defaults = None
airframe_defaults = None
if ulog.has_default_parameters:
system_defaults = ulog.get_default_parameters(0)
airframe_defaults = ulog.get_default_parameters(1)
for param_name in sorted(initial_parameters):
param_value = initial_parameters[param_name]
if param_name.startswith('RC') or param_name.startswith('CAL_'):
continue
system_default = None
airframe_default = None
is_airframe_default = True
if system_defaults is not None:
system_default = system_defaults.get(param_name, param_value)
if airframe_defaults is not None:
airframe_default = airframe_defaults.get(param_name, param_value)
is_airframe_default = abs(float(airframe_default) - float(param_value)) < 0.00001
try:
if param_name in default_params:
default_param = default_params[param_name]
if system_default is None:
system_default = default_param['default']
airframe_default = default_param['default']
if default_param['type'] == 'FLOAT':
is_default = abs(float(system_default) - float(param_value)) < 0.00001
if 'decimal' in default_param:
param_value = round(param_value, int(default_param['decimal']))
airframe_default = round(float(airframe_default), int(default_param['decimal'])) #pylint: disable=line-too-long
else:
is_default = int(system_default) == int(param_value)
if not is_default:
param_names.append(param_name)
param_values.append(param_value)
param_defaults.append(airframe_default)
param_mins.append(default_param.get('min', ''))
param_maxs.append(default_param.get('max', ''))
param_descriptions.append(default_param.get('short_desc', ''))
param_colors.append('black' if is_airframe_default else plot_color_red)
else:
# not found: add it as if it were changed
param_names.append(param_name)
param_values.append(param_value)
param_defaults.append(airframe_default if airframe_default else '')
param_mins.append('')
param_maxs.append('')
param_descriptions.append('(unknown)')
param_colors.append('black' if is_airframe_default else plot_color_red)
except Exception as error:
print(type(error), error)
param_data = {
'names': param_names,
'values': param_values,
'defaults': param_defaults,
'mins': param_mins,
'maxs': param_maxs,
'descriptions': param_descriptions,
'colors': param_colors
}
source = ColumnDataSource(param_data)
formatter = HTMLTemplateFormatter(template='<font color="<%= colors %>"><%= value %></font>')
columns = [
TableColumn(field="names", title="Name",
width=int(plot_width*0.2), sortable=False),
TableColumn(field="values", title="Value",
width=int(plot_width*0.15), sortable=False, formatter=formatter),
TableColumn(field="defaults",
title="Frame Default" if airframe_defaults else "Default",
width=int(plot_width*0.1), sortable=False),
TableColumn(field="mins", title="Min",
width=int(plot_width*0.075), sortable=False),
TableColumn(field="maxs", title="Max",
width=int(plot_width*0.075), sortable=False),
TableColumn(field="descriptions", title="Description",
width=int(plot_width*0.40), sortable=False),
]
data_table = DataTable(source=source, columns=columns, width=plot_width,
height=300, sortable=False, selectable=False,
autosize_mode='none')
div = Div(text="""<b>Non-default Parameters</b> (except RC and sensor calibration)""",
width=int(plot_width/2))
return column(div, data_table, width=plot_width)
def get_logged_messages(ulog, plot_width):
"""
get a bokeh column object with a table of the logged text messages and events
:param ulog: ULog object
"""
messages = get_logged_events(ulog)
def time_str(t):
m1, s1 = divmod(int(t/1e6), 60)
h1, m1 = divmod(m1, 60)
return "{:d}:{:02d}:{:02d}".format(h1, m1, s1)
logged_messages = ulog.logged_messages
for m in logged_messages:
# backwards compatibility: a string message with appended tab is output
# in addition to an event with the same message so we can ignore those
if m.message[-1] == '\t':
continue
messages.append((m.timestamp, time_str(m.timestamp), m.log_level_str(), m.message))
messages = sorted(messages, key=lambda m: m[0])
log_times, log_times_str, log_levels, log_messages = \
zip(*messages) if len(messages) > 0 else ([],[],[],[])
log_data = {
'times': log_times_str,
'levels': log_levels,
'messages': log_messages
}
source = ColumnDataSource(log_data)
columns = [
TableColumn(field="times", title="Time",
width=int(plot_width*0.15), sortable=False),
TableColumn(field="levels", title="Level",
width=int(plot_width*0.1), sortable=False),
TableColumn(field="messages", title="Message",
width=int(plot_width*0.75), sortable=False),
]
data_table = DataTable(source=source, columns=columns, width=plot_width,
height=300, sortable=False, selectable=False,
autosize_mode='none')
div = Div(text="""<b>Logged Messages</b>""", width=int(plot_width/2))
return column(div, data_table, width=plot_width)
| {"/app/tornado_handlers/browse.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/radio_controller.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/edit_entry.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/upload.py": ["/app/tornado_handlers/common.py", "/app/tornado_handlers/send_email.py", "/app/tornado_handlers/multipart_streamer.py"], "/app/tornado_handlers/three_d.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/db_info_json.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/download.py": ["/app/tornado_handlers/common.py"]} |
57,355 | PX4/flight_review | refs/heads/main | /app/delete_db_entry.py | #! /usr/bin/env python3
# Script to remove a single DB entry
import sqlite3 as lite
import sys
import os
import argparse
from plot_app.config import get_db_filename
parser = argparse.ArgumentParser(description='Remove a DB entry (but not the log file)')
parser.add_argument('log_id', metavar='log-id', action='store', nargs='+',
help='log id to remove (eg. 8600ac02-cf06-4650-bdd5-7d27ea081852)')
args = parser.parse_args()
con = lite.connect(get_db_filename())
with con:
cur = con.cursor()
for log_id in args.log_id:
print('Removing '+log_id)
cur.execute("DELETE FROM LogsGenerated WHERE Id = ?", (log_id,))
cur.execute("DELETE FROM Logs WHERE Id = ?", (log_id,))
num_deleted = cur.rowcount
if num_deleted != 1:
print('Error: not found ({})'.format(num_deleted))
con.commit()
con.close()
| {"/app/tornado_handlers/browse.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/radio_controller.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/edit_entry.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/upload.py": ["/app/tornado_handlers/common.py", "/app/tornado_handlers/send_email.py", "/app/tornado_handlers/multipart_streamer.py"], "/app/tornado_handlers/three_d.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/db_info_json.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/download.py": ["/app/tornado_handlers/common.py"]} |
57,356 | PX4/flight_review | refs/heads/main | /app/tornado_handlers/radio_controller.py | """
Tornado handler for the radio controller page
"""
from __future__ import print_function
import tornado.web
#pylint: disable=relative-beyond-top-level
from .common import get_jinja_env
RADIO_CONTROLLER_TEMPLATE = 'radio_controller.html'
#pylint: disable=abstract-method
class RadioControllerHandler(tornado.web.RequestHandler):
""" Tornado Request Handler to render the radio controller (for testing
only) """
def get(self, *args, **kwargs):
""" GET request """
template = get_jinja_env().get_template(RADIO_CONTROLLER_TEMPLATE)
self.write(template.render())
| {"/app/tornado_handlers/browse.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/radio_controller.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/edit_entry.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/upload.py": ["/app/tornado_handlers/common.py", "/app/tornado_handlers/send_email.py", "/app/tornado_handlers/multipart_streamer.py"], "/app/tornado_handlers/three_d.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/db_info_json.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/download.py": ["/app/tornado_handlers/common.py"]} |
57,357 | PX4/flight_review | refs/heads/main | /app/prune_old_logs.py | #! /usr/bin/env python3
# Script to delete old log files & DB entries matching a certain criteria
import sqlite3
import sys
import os
import argparse
import datetime
# this is needed for the following imports
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'plot_app'))
from plot_app.config import get_db_filename, get_overview_img_filepath
from plot_app.helper import get_log_filename
parser = argparse.ArgumentParser(description='Remove old log files & DB entries')
parser.add_argument('--max-age', action='store', type=int, default=30,
help='maximum age in days (delete logs older than this, default=30)')
parser.add_argument('--source', action='store', default='CI',
help='Source DB entry tag to match (empty=all, default=CI)')
parser.add_argument('--interactive', '-i', action='store_true', default=False,
help='Interative mode: ask whether to delete the entries')
args = parser.parse_args()
max_age = args.max_age
source = args.source
interactive = args.interactive
con = sqlite3.connect(get_db_filename(), detect_types=sqlite3.PARSE_DECLTYPES)
with con:
cur = con.cursor()
log_ids_to_remove = []
if len(source) == 0:
cur.execute('select Id, Date, Description from Logs')
else:
cur.execute('select Id, Date, Description from Logs where Source = ?', [source])
db_tuples = cur.fetchall()
print('will delete the following:')
for db_tuple in db_tuples:
log_id = db_tuple[0]
date = db_tuple[1]
description = db_tuple[2]
# check date
elapsed_days = (datetime.datetime.now()-date).days
if elapsed_days > max_age:
print('{} {} {}'.format(log_id, date.strftime('%Y_%m_%d-%H_%M'),
description))
log_ids_to_remove.append(log_id)
if len(log_ids_to_remove) == 0:
print('no maches. exiting')
exit(0)
cur.execute('select count(*) from Logs')
num_total = cur.fetchone()
if num_total is not None:
print("Will delete {:} logs out of {:}".format(len(log_ids_to_remove), num_total[0]))
if interactive:
confirm = input('Press "y" and ENTER to confirm and delete: ')
if confirm != 'y':
print('Not deleting anything')
exit(0)
for log_id in log_ids_to_remove:
print('Removing '+log_id)
# db entry
cur.execute("DELETE FROM LogsGenerated WHERE Id = ?", (log_id,))
cur.execute("DELETE FROM Logs WHERE Id = ?", (log_id,))
num_deleted = cur.rowcount
if num_deleted != 1:
print('Error: not found ({})'.format(num_deleted))
con.commit()
# and the log file
ulog_file_name = get_log_filename(log_id)
os.unlink(ulog_file_name)
#and preview image if exist
preview_image_filename=os.path.join(get_overview_img_filepath(), log_id+'.png')
if os.path.exists(preview_image_filename):
os.unlink(preview_image_filename)
con.close()
| {"/app/tornado_handlers/browse.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/radio_controller.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/edit_entry.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/upload.py": ["/app/tornado_handlers/common.py", "/app/tornado_handlers/send_email.py", "/app/tornado_handlers/multipart_streamer.py"], "/app/tornado_handlers/three_d.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/db_info_json.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/download.py": ["/app/tornado_handlers/common.py"]} |
57,358 | PX4/flight_review | refs/heads/main | /app/tornado_handlers/edit_entry.py | """
Tornado handler to edit/delete a log upload entry
"""
from __future__ import print_function
import os
from html import escape
import sqlite3
import sys
import tornado.web
# this is needed for the following imports
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../plot_app'))
from config import get_db_filename, get_kml_filepath, get_overview_img_filepath
from helper import clear_ulog_cache, get_log_filename
#pylint: disable=relative-beyond-top-level
from .common import get_jinja_env
EDIT_TEMPLATE = 'edit.html'
#pylint: disable=abstract-method
class EditEntryHandler(tornado.web.RequestHandler):
""" Edit a log entry, with confirmation (currently only delete) """
def get(self, *args, **kwargs):
""" GET request """
log_id = escape(self.get_argument('log'))
action = self.get_argument('action')
confirmed = self.get_argument('confirm', default='0')
token = escape(self.get_argument('token'))
if action == 'delete':
if confirmed == '1':
if self.delete_log_entry(log_id, token):
content = """
<h3>Log File deleted</h3>
<p>
Successfully deleted the log file.
</p>
"""
else:
content = """
<h3>Failed</h3>
<p>
Failed to delete the log file.
</p>
"""
else: # request user to confirm
# use the same url, just append 'confirm=1'
delete_url = self.request.path+'?action=delete&log='+log_id+ \
'&token='+token+'&confirm=1'
content = """
<h3>Delete Log File</h3>
<p>
Click <a href="{delete_url}">here</a> to confirm and delete the log {log_id}.
</p>
""".format(delete_url=delete_url, log_id=log_id)
else:
raise tornado.web.HTTPError(400, 'Invalid Parameter')
template = get_jinja_env().get_template(EDIT_TEMPLATE)
self.write(template.render(content=content))
@staticmethod
def delete_log_entry(log_id, token):
"""
delete a log entry (DB & file), validate token first
:return: True on success
"""
con = sqlite3.connect(get_db_filename(), detect_types=sqlite3.PARSE_DECLTYPES)
cur = con.cursor()
cur.execute('select Token from Logs where Id = ?', (log_id,))
db_tuple = cur.fetchone()
if db_tuple is None:
return False
if token != db_tuple[0]: # validate token
return False
# kml file
kml_path = get_kml_filepath()
kml_file_name = os.path.join(kml_path, log_id.replace('/', '.')+'.kml')
if os.path.exists(kml_file_name):
os.unlink(kml_file_name)
#preview image
preview_image_filename = os.path.join(get_overview_img_filepath(), log_id+'.png')
if os.path.exists(preview_image_filename):
os.unlink(preview_image_filename)
log_file_name = get_log_filename(log_id)
print('deleting log entry {} and file {}'.format(log_id, log_file_name))
os.unlink(log_file_name)
cur.execute("DELETE FROM LogsGenerated WHERE Id = ?", (log_id,))
cur.execute("DELETE FROM Logs WHERE Id = ?", (log_id,))
con.commit()
cur.close()
con.close()
# need to clear the cache as well
clear_ulog_cache()
return True
| {"/app/tornado_handlers/browse.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/radio_controller.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/edit_entry.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/upload.py": ["/app/tornado_handlers/common.py", "/app/tornado_handlers/send_email.py", "/app/tornado_handlers/multipart_streamer.py"], "/app/tornado_handlers/three_d.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/db_info_json.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/download.py": ["/app/tornado_handlers/common.py"]} |
57,359 | PX4/flight_review | refs/heads/main | /app/tornado_handlers/common.py | """
Common methods and classes used by several tornado handlers
"""
from __future__ import print_function
import os
import sqlite3
import sys
from jinja2 import Environment, FileSystemLoader
import tornado.web
# this is needed for the following imports
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../plot_app'))
from db_entry import DBDataGenerated
from config import get_db_filename
#pylint: disable=abstract-method
_ENV = Environment(loader=FileSystemLoader(
os.path.join(os.path.dirname(os.path.realpath(__file__)), '../plot_app/templates')))
def get_jinja_env():
""" get the jinja2 Environment object """
return _ENV
class CustomHTTPError(tornado.web.HTTPError):
""" simple class for HTTP exceptions with a custom error message """
def __init__(self, status_code, error_message=None):
self.error_message = error_message
super().__init__(status_code, error_message)
class TornadoRequestHandlerBase(tornado.web.RequestHandler):
"""
base class for a tornado request handler with custom error display
"""
def write_error(self, status_code, **kwargs):
html_template = """
<html><title>Error {status_code}</title>
<body>HTTP Error {status_code}{error_message}</body>
</html>
"""
error_message = ''
if 'exc_info' in kwargs:
e = kwargs["exc_info"][1]
if isinstance(e, CustomHTTPError) and e.error_message:
error_message = ': '+e.error_message
self.write(html_template.format(status_code=status_code,
error_message=error_message))
def generate_db_data_from_log_file(log_id, db_connection=None):
"""
Extract necessary information from the log file and insert as an entry to
the LogsGenerated table (faster information retrieval later on).
This is an expensive operation.
It's ok to call this a second time for the same log, the call will just
silently fail (but still read the whole log and will not update the DB entry)
:return: DBDataGenerated object
"""
db_data_gen = DBDataGenerated.from_log_file(log_id)
need_closing = False
if db_connection is None:
db_connection = sqlite3.connect(get_db_filename())
need_closing = True
db_cursor = db_connection.cursor()
try:
db_cursor.execute(
'insert into LogsGenerated (Id, Duration, '
'Mavtype, Estimator, AutostartId, Hardware, '
'Software, NumLoggedErrors, NumLoggedWarnings, '
'FlightModes, SoftwareVersion, UUID, FlightModeDurations, StartTime) values '
'(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
[log_id, db_data_gen.duration_s, db_data_gen.mav_type,
db_data_gen.estimator, db_data_gen.sys_autostart_id,
db_data_gen.sys_hw, db_data_gen.ver_sw,
db_data_gen.num_logged_errors,
db_data_gen.num_logged_warnings,
','.join(map(str, db_data_gen.flight_modes)),
db_data_gen.ver_sw_release, db_data_gen.vehicle_uuid,
db_data_gen.flight_mode_durations_str(),
db_data_gen.start_time_utc])
db_connection.commit()
except sqlite3.IntegrityError:
# someone else already inserted it (race). just ignore it
pass
db_cursor.close()
if need_closing:
db_connection.close()
return db_data_gen
def get_generated_db_data_from_log(log_id, con, cur):
"""
try to get the additional data from the DB (or generate it if it does not
exist)
:param con: db connection
:param cur: db cursor
:return: DBDataGenerated or None
"""
cur.execute('select * from LogsGenerated where Id = ?', [log_id])
db_tuple = cur.fetchone()
if db_tuple is None: # need to generate from file
try:
# Note that this is not necessary in most cases, as the entry is
# also generated after uploading (but with a timeout)
db_data_gen = generate_db_data_from_log_file(log_id, con)
except Exception as e:
print('Failed to load log file: '+str(e))
return None
else: # get it from the DB
db_data_gen = DBDataGenerated()
db_data_gen.duration_s = db_tuple[1]
db_data_gen.mav_type = db_tuple[2]
db_data_gen.estimator = db_tuple[3]
db_data_gen.sys_autostart_id = db_tuple[4]
db_data_gen.sys_hw = db_tuple[5]
db_data_gen.ver_sw = db_tuple[6]
db_data_gen.num_logged_errors = db_tuple[7]
db_data_gen.num_logged_warnings = db_tuple[8]
db_data_gen.flight_modes = \
{int(x) for x in db_tuple[9].split(',') if len(x) > 0}
db_data_gen.ver_sw_release = db_tuple[10]
db_data_gen.vehicle_uuid = db_tuple[11]
db_data_gen.flight_mode_durations = \
[tuple(map(int, x.split(':'))) for x in db_tuple[12].split(',') if len(x) > 0]
return db_data_gen
| {"/app/tornado_handlers/browse.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/radio_controller.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/edit_entry.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/upload.py": ["/app/tornado_handlers/common.py", "/app/tornado_handlers/send_email.py", "/app/tornado_handlers/multipart_streamer.py"], "/app/tornado_handlers/three_d.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/db_info_json.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/download.py": ["/app/tornado_handlers/common.py"]} |
57,360 | PX4/flight_review | refs/heads/main | /app/tornado_handlers/upload.py | """
Tornado handler for the upload page
"""
from __future__ import print_function
import datetime
import os
from html import escape
import sys
import uuid
import binascii
import sqlite3
import tornado.web
from tornado.ioloop import IOLoop
from pyulog import ULog
from pyulog.px4 import PX4ULog
# this is needed for the following imports
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../plot_app'))
from db_entry import DBVehicleData, DBData
from config import get_db_filename, get_http_protocol, get_domain_name, \
email_notifications_config
from helper import get_total_flight_time, validate_url, get_log_filename, \
load_ulog_file, get_airframe_name, ULogException
from overview_generator import generate_overview_img_from_id
#pylint: disable=relative-beyond-top-level
from .common import get_jinja_env, CustomHTTPError, generate_db_data_from_log_file, \
TornadoRequestHandlerBase
from .send_email import send_notification_email, send_flightreport_email
from .multipart_streamer import MultiPartStreamer
UPLOAD_TEMPLATE = 'upload.html'
#pylint: disable=attribute-defined-outside-init,too-many-statements, unused-argument
def update_vehicle_db_entry(cur, ulog, log_id, vehicle_name):
"""
Update the Vehicle DB entry
:param cur: DB cursor
:param ulog: ULog object
:param vehicle_name: new vehicle name or '' if not updated
:return vehicle_data: DBVehicleData object
"""
vehicle_data = DBVehicleData()
if 'sys_uuid' in ulog.msg_info_dict:
vehicle_data.uuid = escape(ulog.msg_info_dict['sys_uuid'])
if vehicle_name == '':
cur.execute('select Name '
'from Vehicle where UUID = ?', [vehicle_data.uuid])
db_tuple = cur.fetchone()
if db_tuple is not None:
vehicle_data.name = db_tuple[0]
print('reading vehicle name from db:'+vehicle_data.name)
else:
vehicle_data.name = vehicle_name
print('vehicle name from uploader:'+vehicle_data.name)
vehicle_data.log_id = log_id
flight_time = get_total_flight_time(ulog)
if flight_time is not None:
vehicle_data.flight_time = flight_time
# update or insert the DB entry
cur.execute('insert or replace into Vehicle (UUID, LatestLogId, Name, FlightTime)'
'values (?, ?, ?, ?)',
[vehicle_data.uuid, vehicle_data.log_id, vehicle_data.name,
vehicle_data.flight_time])
return vehicle_data
@tornado.web.stream_request_body
class UploadHandler(TornadoRequestHandlerBase):
""" Upload log file Tornado request handler: handles page requests and POST
data """
def initialize(self):
""" initialize the instance """
self.multipart_streamer = None
def prepare(self):
""" called before a new request """
if self.request.method.upper() == 'POST':
if 'expected_size' in self.request.arguments:
self.request.connection.set_max_body_size(
int(self.get_argument('expected_size')))
try:
total = int(self.request.headers.get("Content-Length", "0"))
except KeyError:
total = 0
self.multipart_streamer = MultiPartStreamer(total)
def data_received(self, chunk):
""" called whenever new data is received """
if self.multipart_streamer:
self.multipart_streamer.data_received(chunk)
def get(self, *args, **kwargs):
""" GET request callback """
template = get_jinja_env().get_template(UPLOAD_TEMPLATE)
self.write(template.render())
def post(self, *args, **kwargs):
""" POST request callback """
if self.multipart_streamer:
try:
self.multipart_streamer.data_complete()
form_data = self.multipart_streamer.get_values(
['description', 'email',
'allowForAnalysis', 'obfuscated', 'source', 'type',
'feedback', 'windSpeed', 'rating', 'videoUrl', 'public',
'vehicleName'])
description = escape(form_data['description'].decode("utf-8"))
email = form_data['email'].decode("utf-8")
upload_type = 'personal'
if 'type' in form_data:
upload_type = form_data['type'].decode("utf-8")
source = 'webui'
title = '' # may be used in future...
if 'source' in form_data:
source = form_data['source'].decode("utf-8")
obfuscated = 0
if 'obfuscated' in form_data:
if form_data['obfuscated'].decode("utf-8") == 'true':
obfuscated = 1
allow_for_analysis = 0
if 'allowForAnalysis' in form_data:
if form_data['allowForAnalysis'].decode("utf-8") == 'true':
allow_for_analysis = 1
feedback = ''
if 'feedback' in form_data:
feedback = escape(form_data['feedback'].decode("utf-8"))
wind_speed = -1
rating = ''
stored_email = ''
video_url = ''
is_public = 0
vehicle_name = ''
error_labels = ''
if upload_type == 'flightreport':
try:
wind_speed = int(escape(form_data['windSpeed'].decode("utf-8")))
except ValueError:
wind_speed = -1
rating = escape(form_data['rating'].decode("utf-8"))
if rating == 'notset': rating = ''
stored_email = email
# get video url & check if valid
video_url = escape(form_data['videoUrl'].decode("utf-8"), quote=True)
if not validate_url(video_url):
video_url = ''
if 'vehicleName' in form_data:
vehicle_name = escape(form_data['vehicleName'].decode("utf-8"))
# always allow for statistical analysis
allow_for_analysis = 1
if 'public' in form_data:
if form_data['public'].decode("utf-8") == 'true':
is_public = 1
file_obj = self.multipart_streamer.get_parts_by_name('filearg')[0]
upload_file_name = file_obj.get_filename()
while True:
log_id = str(uuid.uuid4())
new_file_name = get_log_filename(log_id)
if not os.path.exists(new_file_name):
break
# read file header & check if really an ULog file
header_len = len(ULog.HEADER_BYTES)
if (file_obj.get_payload_partial(header_len) !=
ULog.HEADER_BYTES):
if upload_file_name[-7:].lower() == '.px4log':
raise CustomHTTPError(
400,
'Invalid File. This seems to be a px4log file. '
'Upload it to <a href="http://logs.uaventure.com" '
'target="_blank">logs.uaventure.com</a>.')
raise CustomHTTPError(400, 'Invalid File')
print('Moving uploaded file to', new_file_name)
file_obj.move(new_file_name)
if obfuscated == 1:
# TODO: randomize gps data, ...
pass
# generate a token: secure random string (url-safe)
token = str(binascii.hexlify(os.urandom(16)), 'ascii')
# Load the ulog file but only if not uploaded via CI.
# Then we open the DB connection.
ulog = None
if source != 'CI':
ulog_file_name = get_log_filename(log_id)
ulog = load_ulog_file(ulog_file_name)
# put additional data into a DB
con = sqlite3.connect(get_db_filename())
cur = con.cursor()
cur.execute(
'insert into Logs (Id, Title, Description, '
'OriginalFilename, Date, AllowForAnalysis, Obfuscated, '
'Source, Email, WindSpeed, Rating, Feedback, Type, '
'videoUrl, ErrorLabels, Public, Token) values '
'(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
[log_id, title, description, upload_file_name,
datetime.datetime.now(), allow_for_analysis,
obfuscated, source, stored_email, wind_speed, rating,
feedback, upload_type, video_url, error_labels, is_public, token])
if ulog is not None:
vehicle_data = update_vehicle_db_entry(cur, ulog, log_id, vehicle_name)
vehicle_name = vehicle_data.name
con.commit()
url = '/plot_app?log='+log_id
full_plot_url = get_http_protocol()+'://'+get_domain_name()+url
print(full_plot_url)
delete_url = get_http_protocol()+'://'+get_domain_name()+ \
'/edit_entry?action=delete&log='+log_id+'&token='+token
# information for the notification email
info = {}
info['description'] = description
info['feedback'] = feedback
info['upload_filename'] = upload_file_name
info['type'] = ''
info['airframe'] = ''
info['hardware'] = ''
info['uuid'] = ''
info['software'] = ''
info['rating'] = rating
if len(vehicle_name) > 0:
info['vehicle_name'] = vehicle_name
if ulog is not None:
px4_ulog = PX4ULog(ulog)
info['type'] = px4_ulog.get_mav_type()
airframe_name_tuple = get_airframe_name(ulog)
if airframe_name_tuple is not None:
airframe_name, airframe_id = airframe_name_tuple
if len(airframe_name) == 0:
info['airframe'] = airframe_id
else:
info['airframe'] = airframe_name
sys_hardware = ''
if 'ver_hw' in ulog.msg_info_dict:
sys_hardware = escape(ulog.msg_info_dict['ver_hw'])
info['hardware'] = sys_hardware
if 'sys_uuid' in ulog.msg_info_dict and sys_hardware != 'SITL':
info['uuid'] = escape(ulog.msg_info_dict['sys_uuid'])
branch_info = ''
if 'ver_sw_branch' in ulog.msg_info_dict:
branch_info = ' (branch: '+ulog.msg_info_dict['ver_sw_branch']+')'
if 'ver_sw' in ulog.msg_info_dict:
ver_sw = escape(ulog.msg_info_dict['ver_sw'])
info['software'] = ver_sw + branch_info
if upload_type == 'flightreport' and is_public and source != 'CI':
destinations = set(email_notifications_config['public_flightreport'])
if rating in ['unsatisfactory', 'crash_sw_hw', 'crash_pilot']:
destinations = destinations | \
set(email_notifications_config['public_flightreport_bad'])
send_flightreport_email(
list(destinations),
full_plot_url,
DBData.rating_str_static(rating),
DBData.wind_speed_str_static(wind_speed), delete_url,
stored_email, info)
# also generate the additional DB entry
# (we may have the log already loaded in 'ulog', however the
# lru cache will make it very quick to load it again)
generate_db_data_from_log_file(log_id, con)
# also generate the preview image
IOLoop.instance().add_callback(generate_overview_img_from_id, log_id)
con.commit()
cur.close()
con.close()
# send notification emails
send_notification_email(email, full_plot_url, delete_url, info)
# do not redirect for QGC
if source != 'QGroundControl':
self.redirect(url)
except CustomHTTPError:
raise
except ULogException as e:
raise CustomHTTPError(
400,
'Failed to parse the file. It is most likely corrupt.') from e
except Exception as e:
print('Error when handling POST data', sys.exc_info()[0],
sys.exc_info()[1])
raise CustomHTTPError(500) from e
finally:
self.multipart_streamer.release_parts()
| {"/app/tornado_handlers/browse.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/radio_controller.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/edit_entry.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/upload.py": ["/app/tornado_handlers/common.py", "/app/tornado_handlers/send_email.py", "/app/tornado_handlers/multipart_streamer.py"], "/app/tornado_handlers/three_d.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/db_info_json.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/download.py": ["/app/tornado_handlers/common.py"]} |
57,361 | PX4/flight_review | refs/heads/main | /app/plot_app/pid_analysis_plots.py | """ This contains PID analysis plots """
from bokeh.io import curdoc
from bokeh.models.widgets import Div
from bokeh.layouts import column
from scipy.interpolate import interp1d
from config import plot_width, plot_config, colors3
from helper import get_flight_mode_changes, ActuatorControls
from pid_analysis import Trace, plot_pid_response
from plotting import *
from plotted_tables import get_heading_html
#pylint: disable=cell-var-from-loop, undefined-loop-variable,
def get_pid_analysis_plots(ulog, px4_ulog, db_data, link_to_main_plots):
"""
get all bokeh plots shown on the PID analysis page
:return: list of bokeh plots
"""
def _resample(time_array, data, desired_time):
""" resample data at a given time to a vector of desired_time """
data_f = interp1d(time_array, data, fill_value='extrapolate')
return data_f(desired_time)
page_intro = """
<p>
This page shows step response plots for the PID controller. The step
response is an objective measure to evaluate the performance of a PID
controller, i.e. if the tuning gains are appropriate. In particular, the
following metrics can be read from the plots: response time, overshoot and
settling time.
</p>
<p>
The step response plots are based on <a href="https://github.com/Plasmatree/PID-Analyzer">
PID-Analyzer</a>, originally written for Betaflight by Florian Melsheimer.
Documentation with some examples can be found <a
href="https://github.com/Plasmatree/PID-Analyzer/wiki/Influence-of-parameters">here</a>.
</p>
<p>
The analysis may take a while...
</p>
"""
curdoc().template_variables['title_html'] = get_heading_html(
ulog, px4_ulog, db_data, None, [('Open Main Plots', link_to_main_plots)],
'PID Analysis') + page_intro
plots = []
data = ulog.data_list
flight_mode_changes = get_flight_mode_changes(ulog)
x_range_offset = (ulog.last_timestamp - ulog.start_timestamp) * 0.05
x_range = Range1d(ulog.start_timestamp - x_range_offset, ulog.last_timestamp + x_range_offset)
# COMPATIBILITY support for old logs
if any(elem.name == 'vehicle_angular_velocity' for elem in data):
rate_topic_name = 'vehicle_angular_velocity'
rate_field_names = ['xyz[0]', 'xyz[1]', 'xyz[2]']
else: # old
rate_topic_name = 'rate_ctrl_status'
rate_field_names = ['rollspeed', 'pitchspeed', 'yawspeed']
dynamic_control_alloc = any(elem.name in ('actuator_motors', 'actuator_servos')
for elem in data)
actuator_controls_0 = ActuatorControls(ulog, dynamic_control_alloc, 0)
# required PID response data
pid_analysis_error = False
try:
# Rate
rate_data = ulog.get_dataset(rate_topic_name)
gyro_time = rate_data.data['timestamp']
vehicle_rates_setpoint = ulog.get_dataset('vehicle_rates_setpoint')
actuator_controls_0_data = ulog.get_dataset(actuator_controls_0.thrust_sp_topic)
throttle = _resample(actuator_controls_0_data.data['timestamp'],
actuator_controls_0.thrust * 100, gyro_time)
time_seconds = gyro_time / 1e6
except (KeyError, IndexError, ValueError) as error:
print(type(error), ":", error)
pid_analysis_error = True
div = Div(text="<p><b>Error</b>: missing topics or data for PID analysis "
"(required topics: vehicle_angular_velocity, vehicle_rates_setpoint, "
"vehicle_attitude, vehicle_attitude_setpoint and "
"actuator_controls_0).</p>", width=int(plot_width*0.9))
plots.append(column(div, width=int(plot_width*0.9)))
has_attitude = True
try:
# Attitude (optional)
vehicle_attitude = ulog.get_dataset('vehicle_attitude')
attitude_time = vehicle_attitude.data['timestamp']
vehicle_attitude_setpoint = ulog.get_dataset('vehicle_attitude_setpoint')
except (KeyError, IndexError, ValueError) as error:
print(type(error), ":", error)
has_attitude = False
for index, axis in enumerate(['roll', 'pitch', 'yaw']):
axis_name = axis.capitalize()
# rate
data_plot = DataPlot(data, plot_config, actuator_controls_0.thrust_sp_topic,
y_axis_label='[deg/s]', title=axis_name+' Angular Rate',
plot_height='small',
x_range=x_range)
thrust_max = 200
thrust_sp_data = data_plot.dataset
if thrust_sp_data is None: # do not show the rate plot if actuator_controls is missing
continue
time_thrust = thrust_sp_data.data['timestamp']
thrust = actuator_controls_0.thrust * thrust_max
# downsample if necessary
max_num_data_points = 4.0*plot_config['plot_width']
if len(time_thrust) > max_num_data_points:
step_size = int(len(time_thrust) / max_num_data_points)
time_thrust = time_thrust[::step_size]
thrust = thrust[::step_size]
if len(time_thrust) > 0:
# make sure the polygon reaches down to 0
thrust = np.insert(thrust, [0, len(thrust)], [0, 0])
time_thrust = np.insert(time_thrust, [0, len(time_thrust)],
[time_thrust[0], time_thrust[-1]])
p = data_plot.bokeh_plot
p.patch(time_thrust, thrust, line_width=0, fill_color='#555555', # pylint: disable=too-many-function-args
fill_alpha=0.4, alpha=0, legend_label='Thrust [0, {:}]'.format(thrust_max))
data_plot.change_dataset(rate_topic_name)
data_plot.add_graph([lambda data: ("rate"+str(index),
np.rad2deg(data[rate_field_names[index]]))],
colors3[0:1], [axis_name+' Rate Estimated'], mark_nan=True)
data_plot.change_dataset('vehicle_rates_setpoint')
data_plot.add_graph([lambda data: (axis, np.rad2deg(data[axis]))],
colors3[1:2], [axis_name+' Rate Setpoint'],
mark_nan=True, use_step_lines=True)
axis_letter = axis[0].upper()
rate_int_limit = '(*100)'
# this param is MC/VTOL only (it will not exist on FW)
rate_int_limit_param = 'MC_' + axis_letter + 'R_INT_LIM'
if rate_int_limit_param in ulog.initial_parameters:
rate_int_limit = '[-{0:.0f}, {0:.0f}]'.format(
ulog.initial_parameters[rate_int_limit_param]*100)
data_plot.change_dataset('rate_ctrl_status')
data_plot.add_graph([lambda data: (axis, data[axis+'speed_integ']*100)],
colors3[2:3], [axis_name+' Rate Integral '+rate_int_limit])
plot_flight_modes_background(data_plot, flight_mode_changes)
if data_plot.finalize() is not None: plots.append(data_plot.bokeh_plot)
# PID response
if not pid_analysis_error:
try:
gyro_rate = np.rad2deg(rate_data.data[rate_field_names[index]])
setpoint = _resample(vehicle_rates_setpoint.data['timestamp'],
np.rad2deg(vehicle_rates_setpoint.data[axis]),
gyro_time)
trace = Trace(axis, time_seconds, gyro_rate, setpoint, throttle)
plots.append(plot_pid_response(trace, ulog.data_list, plot_config).bokeh_plot)
except Exception as e:
print(type(e), axis, ":", e)
div = Div(text="<p><b>Error</b>: PID analysis failed. Possible "
"error causes are: logged data rate is too low, or there "
"is not enough motion for the analysis.</p>",
width=int(plot_width*0.9))
plots.insert(0, column(div, width=int(plot_width*0.9)))
pid_analysis_error = True
# attitude
if not pid_analysis_error and has_attitude:
throttle = _resample(actuator_controls_0_data.data['timestamp'],
actuator_controls_0.thrust * 100, attitude_time)
time_seconds = attitude_time / 1e6
# don't plot yaw, as yaw is mostly controlled directly by rate
for index, axis in enumerate(['roll', 'pitch']):
axis_name = axis.capitalize()
# PID response
if not pid_analysis_error and has_attitude:
try:
attitude_estimated = np.rad2deg(vehicle_attitude.data[axis])
setpoint = _resample(vehicle_attitude_setpoint.data['timestamp'],
np.rad2deg(vehicle_attitude_setpoint.data[axis+'_d']),
attitude_time)
trace = Trace(axis, time_seconds, attitude_estimated, setpoint, throttle)
plots.append(plot_pid_response(trace, ulog.data_list, plot_config,
'Angle').bokeh_plot)
except Exception as e:
print(type(e), axis, ":", e)
div = Div(text="<p><b>Error</b>: Attitude PID analysis failed. Possible "
"error causes are: logged data rate is too low/data missing, "
"or there is not enough motion for the analysis.</p>",
width=int(plot_width*0.9))
plots.insert(0, column(div, width=int(plot_width*0.9)))
pid_analysis_error = True
return plots
| {"/app/tornado_handlers/browse.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/radio_controller.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/edit_entry.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/upload.py": ["/app/tornado_handlers/common.py", "/app/tornado_handlers/send_email.py", "/app/tornado_handlers/multipart_streamer.py"], "/app/tornado_handlers/three_d.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/db_info_json.py": ["/app/tornado_handlers/common.py"], "/app/tornado_handlers/download.py": ["/app/tornado_handlers/common.py"]} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.