r/hobbycnc • • Oct 24 '24

Python > G-Code. Change my mind

Hello /r/hobbycnc ,

I'm creating a programming paradigm intended for running robots with Python; specifically non-cartesian CNC machines like robot arms with bespoke toolheads and functions.

I'm looking for what kind of syntactic sugar you all like (or would like to see).

a typical line of gcode has the structure of G1 | X25 | Y15 | F1200 G1 X25 Y15 F1200 function name {space} kwarg {space} kwarg basically a function followed by nothing or any number of kwargs typically denoted by a single letter

The trouble is that pyton does not execute code in a way needed for these machines. So let's build up from the ground. Fundamentally I think we want something similar.

G1 X25 F1200 means that we want the machine to move (in a linear fashion) to the position 25 units on the axis 'X' at a speed of 1200 units/time.

My proposed new version would be {"cmd": "move.linear", "x": 25, "feed": 1200} There are a lot of reasons to have something that's serializable, most notably flow control.

Question 1: @Machinists if you saw all these commands would you be able to read them?

line1: compiled code, think of this like assembly
line2: python function

{"cmd": "move.rapid", "x": 0}  ==> G00 X0
move.rapid(x=0) ==> G00 X0

{"cmd": "spindle", "arg": True} ==> M03
spindle.on() ==> M03

{"cmd": "spindle", "state": True, "direction": "cw", "speed": 5000} ==> M03 S5000
spindle.on(direction='cw', speed=5000) ==> M03 S5000

{"cmd": "sleep", "seconds": 1.5} => G04 P1500
sleep(1.5) => G04 P1500

Question 2: Machinists know what Gcode is, does this need a new name? Since Gcode is already so ill-defined, is it ok to call it Gcode?

{"cmd": "move.rapid", "x": 0}
{"cmd": "spindle", "arg": True}
{"cmd": "sleep", "seconds": 1.5}

Fundamentally we have bits of json separated by '\n' newline characters.


Advanced questions

In the above examples imagine we have a carefully crafted namespace and the engine running above code does type introspection and can eval() if desired

Referenced before was the need for flow control. ie. we can't just execute an entire program, sometimes our script needs to wait, like when a machine needs to move from one place to another, that takes time.

Question 3: Generators appear to be the best execution scheme. If there are other methods that I am unaware of please let me know.

Fundamentally at the top level this leaves us with robot.run(iterable)

Now we've seen what the compiled version looks like, how about some python code

Somewhat contrived Robot Bartender Example

def get_ice():
    yield move(**ice_location)
    yield ice_machine.vend()
    yield move(**after_ice)

def pour(ounces: float): 
    yield move(**pour_location)
    yield move(**bottle_pour)
    yield wait_until(scale, lambda val: val > ounces) 
    yield move(**bottle_up)

def bottle_handler(bottle: str, operation: str):
    if operation == 'pick':
        yield move(**bottles[bottle])
        yield gripper.close()
        yield move(**bottle_rack_clear)
    elif operation == 'place':
        yield move(**bottles[bottle])
        yield gripper.open()
        yield move(**bottle_rack_clear)

def make_drink(bottle: str, ice: bool):
    if ice:
        yield from get_ice()
    yield from bottle_handler(bottle, 'pick')
    yield from pour(5)
    yield from bottle_handler(bottle, 'place')

Play with a browser based version of this code here

https://floe.evezor.com/pyscript/671616e5fd297e7dcanv?core=mpy

Question 4: Do you understand yield and yield from? How does writing scripts as generator objects make you feel?

Thank you so much for your time!

4 Upvotes

66 comments sorted by

26

u/madbobmcjim Oct 24 '24

You probably need more preamble here, what problem are you trying to solve? A lot of us here probably don't interact with gcode much unless something goes wrong, I usually just take the output of Fusion and pass it to my machine. So I'm not sure the problem you're working on.

Gcode isn't exactly pretty or easy to understand without a lookup table, but it works. Is your goal to make it more readable?

Also, a lot of your questions are coding questions, and so you're probably going to have a limited number of people here who can help.

16

u/metisdesigns Oct 24 '24

I'm not sure the OP understands what Gcode is used for.

It's simply the instructions for the machine to follow, in as simple a fashion as possible to make it as quick to process as possible.

It sounds like they want to be able to read it as a human.

0

u/anfroholic Oct 24 '24

I am a journeyman machinist. I've also built quite a few machines and run others. I would consider my native programming language to be gcode.

Quick to process is not really an issue as very powerful computers are so cheap now. (there's more power in my watch than my first machines)

Functionally gcode and my proposed codes are both serialized commands that can then be interpreted to do any number of things. Gcode, works great for what it's meant for but falls a little flat when you try to do more programmatic things.

And readability is important. Prusa of 3d printers just came out with a new binary gcode format, aimed more specifically at file size, but will just state again, that looking at code that comes out of CAM tools or slicers, is mildly out of scope for what I'm referring to here and is what most machinists are used to (and for good reason!)

Thank you for taking the time to give an insightful comment as I get better at describing this!

-1

u/anfroholic Oct 24 '24

Thanks for your insight.

You probably need more preamble here,

I didn't want this post to get too long, so probably missed a few of the most key points.

A lot of us here probably don't interact with gcode much unless something goes wrong, I usually just take the output of Fusion and pass it to my machine. So I'm not sure the problem you're working on.

This is very true as well. My first career was as a machinist and I'd also consider my first programming language to be gcode. Having given some public talks lately, I do realize there is a kind of disconnect at some kind of fundamental level. At be beginning of my talk, I lamented the fact that I learned gcode in college without any need for it in my professional life, then towards the end of the talk, I was referring to code that is very much like gcode and actually writing it.

To go from something like Fusion to a machine, in all actuality there is little reason for a person to get involved and even look at it unless there is a problem.

Gcode isn't exactly pretty or easy to understand without a lookup table, but it works. Is your goal to make it more readable?

I also gave a talk about gcode some years ago and made a joke that one day someone suggested putting the punch cards into a computer and they decided to call it gcode... And no one changed it since.

For robust toolchains, what we have is fine, but completely falls on its face when you try to do something novel.

Having taught coding to a few people about coding, I emphasize readability is what good coding is. Furthermore, gcode is limiting in it's forms of expression, even for something simple like making a toolchange macro from my other comment on this thread. Not to mention there is no conceivable way to write something like "Look up some things on the internet, then write me a post-it with the current time and the weather outside"

Also, a lot of your questions are coding questions, and so you're probably going to have a limited number of people here who can help.

Yeah, I do know that. You'd actually be pretty surprised how wide the gulf is on both sides (programmers, machinists) as gcode and languages like python inherently function is such wildly different ways.

Hope I was able to give you a little more understanding of the problem and thank you so much for your comment. As I keep talking to people I think I'm finally starting to wrap my head around ways to explain it better. Thank you

6

u/pr06lefs Oct 24 '24

Yeah gcode is deterministic, while you're looking for something that is more of a robotics language. A gcode program will do the same thing every time, barring crashes, while you're looking for something dynamic that will move based on sensor input, like 'find where a glass is on the table and then pick it up'.

That's a legit need, but also in some ways a downside for machinists. Having gcode do the same thing on any well calibrated machine is a feature, not a bug. Machinists want consistency, not dynamic control.

You may even want to go as far as having control logic at a finer level than gcode allows - instead of simple movements, altering servo acceleration and velocity during a move, or not having 'moves' at all but responding frame by frame to inputs with motor setting changes.

2

u/anfroholic Oct 24 '24

I pretty much agree with you on all points. And am for sure looking for things that are more of a robotics language.

As things move forward, I think it's going to become increasingly valuable to be able to run/ program/operate machines of all types. Machinists have a special place in my heart, as it was my first career. I would like to see something that is palatable enough that machinists could and would cross that divide, as in actuality they're perfectly positioned to make a jump like that.

I don't think I answered your question exactly, but hope it's close enough.

Thank you for your time and comments!

2

u/Onphone_irl Oct 24 '24

so I was planning on doing a project with an arduino and a cnc shield. I've yet to research how a cnc shield works, but it seems like maybe this is an application. Python runs on raspberry pi, seems like it would be better suited. many things can be done using x,y and z motion and there are cnc shields available...if you're making it seemless to pass code to cnc you're onto something.

2

u/anfroholic Oct 24 '24

Different hardware, but effectively yes. Very close to that.

2

u/start3ch Oct 24 '24

Why not just add a more readable interface to Gcode?

Ultimately you need to send commands in a way the machine understands, and currently that’s just commanding positions, or predetermined routines that the machine understands like curved paths.

You could also just add your own Gcodes to the machine firmware, to do more complicated types of movements.

2

u/anfroholic Oct 24 '24

Some things are more nuanced and is more than just making gcode more readable. Some of it is to allow people to be more expressive.

With a robot arm, you could have a move like move.linear(x=10) but the planner will see a ton of little small moves that interpolate a straight line because robots have no concept of a straight line, to say nothing of general IO. There are many gcode firmwares out there, but when you don't know a whole lot they can seem very daunting, and it's not clear right away how to easily add functionality without unintentionally breaking something else.

Thank you for your insight!

3

u/madbobmcjim Oct 24 '24

OK, I think I'm getting a little closer to what you're talking about. For my machine the macros I've written are a mix of gcode and C#, as that's what the system is built in and there's no standardized way of doing it.

I'd love to integrate my CNC with MQTT so it can appear in HomeAssistant...

But I'm still not sure what changing gcode does here, when I've written the C# macros it literally calls Gcode for machine movements, so why is that a problem? Or I guess, why is that enough of a problem that it needs a while new way of programatically expressing machine motion?

1

u/anfroholic Oct 24 '24

Wow! Yes! I love all those ideas!

I'm still trying to find ways to describe this effectively, so I hope I get this right.

The changing of gcode has a little more to do with what I'm going to refer to as the 'lifetime' of your code/program/macro.

Gcode doesn't really have any notion of return and branching. (I do know there are counter examples, but none of them are very user friendly).

To channel some of the other comments in this post, it would be nice to have a single place where you can write programmatic expressions, and motion like commands without context switching. And to state some things a little more clearly because you seem more well versed, any of the calls that just look like json are what a serialized/compiled line of gcode would look like, but in a handwritten script, you'd likely only see function calls.

I love your ideas and thank you again!!

8

u/Cyphco Oct 24 '24

Its basically what CnC Manufacturers have been doing since always. No matter if you look at Haidenhain, Simens, Hurco they all provide some kind of abstraction layer on top to make it easier to comprehend. Its still important to have a way to look under the abstraction for niche problems. So it would be nice to have both, the abbr. and the pure gcode

3

u/anfroholic Oct 24 '24

That's effectively what I'm trying to do here. At the end of the day there is always some bundle of hardware and sensors that is your machine. Effectively calling on them, creating and understanding the abstractions is the root of what I'm trying to get at.

Thank you for the way you so concisely described that. I will be using that later.

5

u/saltedfish Oct 24 '24

I'm not sure what problem this is intended to solve. I've been a machinist for 10+ years and in all the parts I've made gcode has been perfectly adequate.

I'm all for innovation and trying new things, but something like

M3 S1500;

seems a lot easier to understand (and type) than whatever it is you have going on here. Obviously if you're doing robotics you're going to need something with a vastly different level of complexity because of the motions involved. But for simple machining? I'm not sure what I read up there would necessarily be easier or faster to parse.

Gcode is honestly way more flexible than I think most people realize. It has for and while loops, you can compare values and increment/decrement. That gets you pretty far. At a previous job running wire EDM, I wrote from scratch my own coreless hole program that was less than 1500 characters and allowed me to creep up on dimensions and hold .0001" if I wanted. It has lead ins and lead outs for all the moves and I could iterate it as many times as I wanted across a part.

The point being, there's actually quite a lot you can do with gcode if you're thoughtful about it. It doesn't have to be just "to here, now go here."

1

u/anfroholic Oct 24 '24

It is intended to solve some of the more complex problems you elude to further in your comment. Over my years, my CAM software and I wrote billions of lines of gcode and like 10,000 unique programs. For the stuff that it was designed for it is perfectly adequate.

I think I need to be more careful to exclude machines and processes that are already very well defined.

I like your program. And to some extent I like the crazy gcode programs that JohnGrimsmo creates to make his knives, but I would never want to write one as the gcode syntax leaves a lot to be desired even in the more simple things like variables and loops.

Thank you!

2

u/[deleted] Oct 24 '24

[removed] — view removed comment

1

u/anfroholic Oct 24 '24

I am also aware of some gcode parsers ability with loops, variables and goto.

On the specific case of goto, and I don't want to be too harsh, but there are very good reasons why it does not exist in any new language.

Additionally I think I need to do a better job of defining scope when bringing this up. Thank you for your comment, and I'll be honest I'm loving some of the stories you all have showing the creativity of using the tools you've been given. Thanks

2

u/Narrow-Chef-4341 Oct 25 '24

G-code was never intended to be a Turing complete language. It’s simply a tool that has incrementally and iteratively improved over time.

Your ideas are fascinating but in the end, you are asking about adding in a lot of shiny parts that nobody was asking for. Sorry to break it to you, but it really feels a lot like you are going to be that guy who puts a lift kit and 34” tires on a Miata… it’s impressive, but everyone still has to ask ‘but… why?’

If that’s is your new hobby - have at ‘er. Do whatever you want for fun. But ease up a bit on the judgments - farm tractors don’t have the fancy run flat or z-rated speed tires, because they don’t have to.

You’ll get a lot more in-tolerance parts made by 100 experienced machinists using goto than you will putting 100 engineers in front of a CNC and saying ‘learn this new programming language’ (hint: the Engineers are the ones that spent the first ten years on the job designing impossible to manufacture parts, start there…)

4

u/hlx-atom Oct 24 '24

You are writing yaml/json. Don’t write your own serialization filetype if you are gonna do this.

3

u/pokemaster0x01 Oct 24 '24

Strictly speaking, it seems to be closer to JSON Lines (jsonl) rather than bare JSON.

1

u/anfroholic Oct 24 '24

Whoah!!! Yes! I never knew about that. I'll look into that more. Thank you!

0

u/anfroholic Oct 24 '24

I've been waffling on this one quite a bit. The biggest argument I have against json is commas and more so trailing commas. A parser is just 2 lines.

for line in gcode.split('\n'):
    execute(json.loads(line))

And it's even less if it's read from a file. I'll keep gathering opinions on it. Thanks for the comment.

2

u/hlx-atom Oct 24 '24

Then use yaml if commas are your complaint.

1

u/anfroholic Oct 24 '24

yaml is a contender. I'll definitely give it another look. I've heard recently about some of the built in features that both intrigue and terrify me, like function calls built into the language. Thanks

2

u/hlx-atom Oct 24 '24

Yaml is used everywhere as a generic instruction/configuration language.

Using yaml instead of gcode is a cool idea. Don’t make your own. Much less cool.

1

u/anfroholic Oct 24 '24

I hear that and is part of why I've been asking questions. One of the parts I have failed to mention is if you have an entire program written as a json object, or yaml, you can't handle that on embedded and other resource constrained systems, which is a requirement for the things I'm working on. And someone above mentioned JSON Lines (jsonl) which, for better or worse, someone not only has created, but taken the time to document.

Thank you again for the input.

2

u/hlx-atom Oct 24 '24

There is also protobuf and some more optimized formats for compressed serialization if you need to send the data around quickly. Or minimize space on the microprocessor.

1

u/anfroholic Oct 24 '24

I'm less concerned about space than I am about legibility and general understanding. And protobuf is good but maybe not for this particular use case. I will go as far as to contend that json leaves a lot to be desired as well, but shares shape with dictionaries and so is easy to understand

4

u/mil_1 Oct 24 '24

So custom canned cycles? I run machines and write gcode foe a living and none of this is appealing to me. But I guess you're doing a dif use?

1

u/anfroholic Oct 24 '24

That's probably correct. I would never expect for you to go up to your Fanuc machine and start typing any of this in. But custom canned cycles are the easy mode stuff of what I'm trying to get at.

Thank you!

1

u/mil_1 Oct 24 '24

Just curious. The whole post was written with chatgpt right?

1

u/anfroholic Oct 25 '24

nope, just me. Not a bot

3

u/WillAdams Shapeoko 5 Pro Oct 24 '24

FWIW, I've been working on a similar project:

https://github.com/WillAdams/gcodepreview

and am currently re-writing it entirely in Python.

You can see a bit of discussion on it at:

https://old.reddit.com/r/OpenPythonSCAD/

and

https://forum.makerforums.info/t/rewriting-gcodepreview-with-python/88617

That said, the current focus is on writing out DXFs so as to allow using a traditional CAM tool.

1

u/anfroholic Oct 24 '24

Neat! I've starred it so I can go and have a look later.

Also love to see other old.reddit users.

Thank you

2

u/WillAdams Shapeoko 5 Pro Oct 24 '24

Another thing to check might be BowlerStudio:

https://commonwealthrobotics.com/

3

u/alcaron Oct 24 '24

I keep reading your comments and still just. You don’t give any specific examples of what “novel” things you are trying to do that in any way are the “fault” of gcode. The command interpreter on the machine side and the physical nature of what you are doing is why gcode is the way it is and ultimately an entire language just to do some niche things feels like you could just write an interpreter that does what you want.

0

u/anfroholic Oct 24 '24

You don’t give any specific examples of what “novel” things you are trying to do that in any way are the “fault” of gcode.

I've tried pretty hard to knock gcode too hard. But in some of the ways people could talk about assembly in the same way. Does that mean that no one should ever write assembly? Not necessarily, and there is a benefit to knowing it. But i would say that the bartender example is fairly novel, we've got branching, we've got realtime controls waiting for sensors and macros. Nothing there is incredibly difficult, but expressing it in gcode would not be fun, if at all possible without writing your own firmware.

you could just write an interpreter that does what you want.

Or still not and just lean on python.

Thanks for taking the time to comment, I think I'm starting to get a feel for where people are and how they interpret different aspects.

2

u/alcaron Oct 25 '24

I feel like you think you are a bit more clever than you seem. Once again you haven't given any example of what gcode CANT do, or. why Python is better.

"Or still not and just lean on python." why create an ENTIRELY new command language? You have not once said "because you can't do X with gcode". You mention "programmatic' stuff and macros, but one of MANY examples why that is not true is klipper.

You can EASILY utilize an array of sensors, you can EASILY introduce logic for "programmatic" stuff.

I don't really know how to change your mind when the premise is kind of invalid and your ego seems to be in the way of you seeing that.

0

u/Straight-Subject-770 May 13 '26

Reading through some of these a year+ after it almost feels like the mill lathe paradigm easy to start hard to master harder to start easier to master. It feels he hit a limit wall on gcode and is trying to use another code to get past it but for what actual reason.

5

u/pokemaster0x01 Oct 24 '24

No, it is not okay to call your json-lines thing "GCode" and why would you even want to. Call it machine code or movement code or something. Your "GCode" doesn't have any G## codes in it. Concrete reason why: file extensions - if you name it file.gcode, then try and open that in, for example, "Prusa GCode viewer," it will just choke. If you want a better name call it JCode (for JSON[Lines] [Movement] Code).

That said, the Python idea is good. It makes it much more readable, if you ask me. I think there are some other projects out there doing similarly (I think someone else linked one). The JSON not so much, unless you need something GCode really can't do, or just want to have some sort of readable "assembly" (with the ability to disassemble GCode as well, of course). But at that point why not "disassemble" to the even more readable Python code?

1

u/anfroholic Oct 24 '24

I'm working my way down through the comments after running some errands and answered a bit there.

I did not know about JCode that actually seems very appropriate.

Thank you for liking the Python side. The JSON side is kind of an artifact. Part of this project is about networked devices, so the ability to serialize for some kind of Remote procedure call is important. Another added benefit is to have some things pre-compiled if there is some reason, like memory overhead on resource constrained devices, that is an option as well.

But at that point why not "disassemble" to the even more readable Python code?

My initial thought was the fact that it just looked like python dict makes it second nature to someone who's used to looking at it, along with the fact that even 'in' python you're likely just throwing a dict at some function anyways.

You've given me a lot to think about, so thank you for everything!

1

u/pokemaster0x01 Oct 25 '24

JCode is something I made up (not a standard thing - though JSON Lines is). As best I can tell nothing is really using that as an extension, though, so you should be good to go in using it.

For networked devices I can see the appeal. For serial devices not so much (even GCode, which is pretty optimally compact for a text format, can strain a serial connection if arcs have been turned into linear moves with a high resolution).

Best of luck to you!

2

u/[deleted] Oct 24 '24

Okay I'm a software engineer but no expert on G-Code (i.e. know nothing more than what it basically is.)

Don't call your code G-Code. It's not G-Code even if it's a 1-to-1 translation, so why cause confusion?

Taking your example of:

{"cmd": "move.linear", "x": 25, "feed": 1200}

The following reads much better IMO:

move.linear(x=25, feed=1200)

Since the idea here is to make things as easy to read as possible (correct me if I'm wrong), you should not put the cart before the horse and decide on JSON (or whatever that format is).

2

u/anfroholic Oct 24 '24

move.linear(x=25, feed=1200) is what you'd type in a .py file if that's how you've written your program. Even in that case dict(cmd='move.linear', x=25, feed=1200) # changed to explicitly state that it is a dict is fed into the motion machine. Which still may take that and further process into more commands implicitly.

So the python is just python and the JSON is a serialized form that can be transported over networks/ busses/ files. And also at that point the JSON could be thought of as machine or assembly code.

Someone else has brought to my attention that JSON Lines (jsonl) already exists and that is what it is.

Since the idea here is to make things as easy to read as possible

Initially I was hoping for something that would make the machinists feel like it wasn't so far of a jump and something they could 'use' without having to become 'programmers' even if that's what they're doing.

There have been a ton of great comments (yours included) here and it's going to take me a bit to process it all. Thank you

1

u/Nitronium777 Oct 24 '24

Gcode syntax is a little easier to read, but it doesnt encapsulate each action as well. Its rare to manually write long GCode programs though. Also is your idea to run python on the mills? Or just interpret it? (In which case this project becomes less about python and more just a different command format style). Im worried that python is simply too heavy to run on the systems. But a human->python->gcode workflow could work

1

u/anfroholic Oct 24 '24

Im worried that python is simply too heavy to run on the systems.

Python runs great on embedded systems with micropython Not too heavy at all.

Its rare to manually write long GCode programs though. Also is your idea to run python on the mills? Or just interpret it?

Agreed on the length thing, and usually with high level languages you're trying to use conventions that keep it from being too long. You can use it for mills, it will do that just fine. And in the hobby cnc space it would help to create add-ons like tool changers or other more bespoke hardware/ devices/ macros.

Thank you for the comment.

1

u/anfroholic Oct 24 '24

Not sure if these initial downvotes are just from the tongue in cheek title, or what.

In this and other forums I have seen many who run into problems when trying to make macros for something like tool changes, especially when you try to add a sensor for something like checking the tool has actually been grabbed correctly.

With something like gcode and grbl there is no plain way to make something like this without great effort and non-conventional design.

6

u/naught-me Oct 24 '24 edited Oct 24 '24

>> Not sure if these initial downvotes are just from the tongue in cheek title, or what.

It's because there's so many words. It's like you asked ChatGPT to help fill your post with rambling.

Also, it's barely relevant to most people here. They don't type g-code, their CAM program exports it.

Look into robotics motion control. People already do what you're talking about.
Look into the LinuxCNC Python interface.

3

u/tbst Oct 24 '24

Exactly. It’s like asking people what they think about CANBUS for the cars. They don’t care, nor should they. They get in their cars and drive. 

1

u/anfroholic Oct 24 '24

Yes and no, like I've stated in some other responses.

There is no way, in most gcode paradigms. To write something like the bartending example I wrote above. At least not something that's user friendly to read or write

Thank you for the reply though.

2

u/ekoneko Oct 24 '24

Regardless of how amazing and adopted by industry your python abstraction paradigm is, it will have to generate gcode at the end of the day if you want it to work on the vast majority of everything out there.

It sounds like you're looking to make a python-based abstraction layer that allows fast generation of parametrically defined operations.

Decent idea. It's not replacing gcode though.

That doesn't mean it's not worth doing, Fortran didn't replace assembly, it just made things easier.

Seems like a good fit to work with something like build123d / cadquery on the modelling side.

1

u/anfroholic Oct 24 '24

It sounds like you're looking to make a python-based abstraction layer that allows fast generation of parametrically defined operations.

Effectively, yes. I think that's a wonderful way of summing this up.

Decent idea. It's not replacing gcode though.

That doesn't mean it's not worth doing, Fortran didn't replace assembly, it just made things easier.

Again, I really like the way you explain things. And at the end of the day, making things easier is most of the the primary goal of what I'm doing.

Thanks for the eloquent descriptions, and I've never heard of build123d or cadquery. I'll have to look those up!

1

u/anfroholic Oct 24 '24

I definitely did not use an llm to generate my question.

I also do understand that it's barely relevant to most of the people here as this has little to nothing to do with CAM and related programming methods.

I did not know about the LinuxCNC Python interface and will be looking into that. I've used LinuxCNC in the past, but was unaware of that module, so thank you for pointing that out and for your comment.

3

u/naught-me Oct 24 '24 edited Oct 24 '24

Another thing is, Python is also too slow.

You might use it as an organizing/communication layer, basically not much more than g-code is (machines don't run g-code, they run C/C++, and g-code gets piped into C/C++ data structures). But, it's too slow to run the actual real-time parts of motion control.

So, you're basically talking about changing upholstery, not machinery.

And, there are probably some Python to g-code translators. I wrote a motion control system (C++ core, Python wrapper/planner), and it might've been 5k or 10k lines of code, and I don't think the g-code translator (just for g0/g1 moves) was more than 25 or 50 lines of code. So, if what you're doing could be accomplished by writing in Python and doing a g-code export, it might actually be easy.

1

u/anfroholic Oct 24 '24

Python is also too slow [...] too slow to run the actual real-time parts of motion control.

Python is faster than people often give credit for, but I will agree with you that it may not have a place on some components, but must also acknowledge that some Python calls are all C under the hood see json, numpy, etc.

I have no illusions (or desire) that the likes of Fanuc pick up anything I'm doing. And agree completely there is no need if what I was seeking could just be a translator that simply exports. (That's super awesome you made one too!)

What I'm looking for is something that can be more dynamic as a high level language. At a fundamental level many (all?) the motion commands will simply compile down to gcode or something similar just like modern languages still basically compile to assembly. No one should write assembly, but no one can challenge its existence either.

Summing up I think a machine could look like this

[Host] -> [Motion Planner] -> [Motor controllers]

Where something like gcode gets fed to the planner and host is something that's usually not part of the machine directly. What I've been building has the host as part of the machine itself, and this is where all user interaction takes place.

Another comment here said: "It sounds like you're looking to make a python-based abstraction layer that allows fast generation of parametrically defined operations. " So basically that, along with some more dynamic control based on real-time information or the like.

Thank you again

2

u/naught-me Oct 24 '24 edited Oct 24 '24

>> more dynamic control based on real-time information

This is hard. The rest is easy enough, but, generally, on the other side of g-code is black box. You tell it what to do, but not when, and even though you tell it "exactly", it has algorithms that have to approximate things on some level (or runs fancy acceleration algorithms). And, it gives you back, like, 20 or 50 updates per second about where it is, with no data about what lines it's actually executed, because those lines get destructively ingested (when they go from parse->plan, the machine no longer remembers anything about the command that was parsed, and only has the plan to work with, on all GRBL-based systems, at least).

LinuxCNC is the only easy way I've found.

1

u/anfroholic Oct 24 '24

It is hard, I'll give you that, but there's a lot of fun things I've done and want to make it easier for others to do the same.

I have never really cared for LinuxCNC for whatever reason. Currently I have FluidNC as the motion core. As long as you keep the planner topped off, things are just peachy. Bart Dring, the guy who manages and writes most for it is one of my friends.

2

u/naught-me Oct 24 '24

FluidNC has the limitations I mentioned regarding realtime stuff. I spent a fair amount of time trying to get realtime reactivity out of FluidNC specifically. There's some things it's very bad at, like realtime direction changes (you have to keep the queue full, and if you're moving fast, that's a fair amount of motion before you can even begin to change directions). And, it's got the black-box thing going on, which you can mostly get your way around, if 20hz or 50 hz updates are good enough for your application, and if you aren't re-crossing the same points in quick succession (like, you only get position out, so, if one position does not map exactly to one point in time, you know where the machine is but not when it is).

Would be happy to see what you come up with, though. I think there's a lot of use-cases for a Python wrapper over FluidNC - its limitations probably won't matter for most projects.

1

u/anfroholic Oct 24 '24

I am aware of some of those limitations with FluidNC, some of the problems come from it not being happy if the planner isn't full, which by it's very nature means that your python/gcode is running in the future, with no good way to dump the buffer if you want to change course. (I think we're saying the same thing?) And no that's not something I'm going for at the moment and most of what I have planned, this limitation is probably just fine.

Thanks for the input and I'll keep making some updates if you wall will have me.

2

u/naught-me Oct 24 '24

Yeah, I'd at least try whatever. I sometimes think about going back to work on my FluidNC Python wrapper. I ended up using generators for mine, too. I'll think about publishing my work. I've probably got something that would be useful to you.

→ More replies (0)

2

u/divsmith Oct 24 '24

Not directly related, but I've thought about this kind of abstraction layer for industrial programming on top of ladder logic. Cool idea, following. 

1

u/mattyell Oct 24 '24

Looks like scripting a program to me

script

1

u/WoodArt3D Oct 25 '24

So here is the problem with this from my perspective:

What you are describing is just more of a gcode generator. To be a truly new system, you would have to also write a corresponding embedded OS to interpret the new python code and translate it to stepper control signals through drivers and queue commands. At that point, why would you be using classes in your code at all? The code in your file could just read x100 y50 F500. The code interpreter on the controller then reads this and makes the function calls. Oh wait, now it's Gcode. The controller reads x100 and then calls some internal functions to create a member for 100. something like movement.xmove 100. We don't see any of that because it is behind the scenes in the controller.

The other problem you will run into is that even if you do write a new embedded OS to accept your readable code, well now you have to program a new post-processor for every major cam software or else no one will be able to generate files for your new controller. Unless you are solving some major problems or have some amazing features, it's a really tough sell.

What it sounds more like you are trying to do is come up with a scripting language in Python that writes gcode. This is not so hard to do, but I'd rethink your approach a bit. Instead of using commands like "move x,y", you would need to add more advanced functionality to make it useful. How about something more like this:

Speed=500 Zstep=.25

DO(3x) Square (perimeter 30, type pocket) Circle (radius 10, type=profile, offset=.0625) ARC (radius 30, degrees=45 type=xx) Wave(period=1, length= 5, amplitude=2, type=sin) Zstep(-) LOOP Etc etc etc

FYI, there are some CAM packages out there for free that are already scripted like this. I played with one a while ago, but I can't remember the name. May have been FreeCAD.

1

u/Icedecknight Oct 25 '24

Sorry I didn't read all of it, but to the first question would be a yes for me, BUT I have a long history of programming in C,C#,Javascript, etc. (Including Gcode and macrocodes)

I would encourage you to use proper terminology and define what functions mean and compare them to canned cycles. Machinists know what a g84 does, and clarifying that is technically what a function is would help them a lot.

Aso F1200, with G20 (sets the coodrdinates to move in inches, G21 for metric), would move at 1200 tenths a minute or 1.2 inches a minute. You probably meant to put "F1200." A period is needed at the end of the number. Otherwise, the machine would move at the lowest possible increment.

I've tried a similar thing with Macro callouts in my code, and even though it seems like basic algebra to us, they dont understand things like

While[#100>#101]GOTO206 GOTO220 N206 G00 X#201 Y#202 Z1. S#110 M03

Etc. Even if it's all cleanly written out in comments at the top of the program.